C#扩展方法与特定属性
问题描述:
对象我创建了一个扩展方法,将告诉我的每一个对象的大小创建 这样的:C#扩展方法与特定属性
public static int CalculateKilobytes(this object notSuspectingCandidate)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, notSuspectingCandidate);
return stream.ToArray().Count()/1000;
}
}
由于我使用serializaion,不是所有的对象将是能够回答答案,只有可串联的答案。有没有办法将此方法附加到可以序列化的对象?
答
您可以使用Type.IsSerializable Property。
public static int CalculateKilobytes(this object notSuspectingCandidate)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
if (notSuspectingCandidate.GetType().IsSerializable) {
formatter.Serialize(stream, notSuspectingCandidate);
return stream.ToArray().Count()/1000;
}
return 0;
}
}
答
如果您计划在稍后再次序列化它,那么序列化仅用于获取其大小的对象是非常糟糕的做法。
请谨慎使用。
扩展方法将应用于所有对象,您必须检查它是否具有自定义属性。
该检查可以完成这项工作。
if (notSuspectingCandidate.GetType().GetCustomAttributes(typeof(SerializableAttribute), true).Length == 0)
{
return -1; // An error
}
另一种方法是将扩展方法放入ISerializable并在所有需要的类型中使用该接口。
public static int CalculateKilobytes(this ISerializable notSuspectingCandidate)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, notSuspectingCandidate);
return stream.ToArray().Count()/1000;
}
}
嗨,感谢您的快速反应,我有几种方法来防止异常(也与try/catch)。我希望防止扩展方法出现在编译时不可序列化的对象中 – user1166664 2012-03-29 16:10:16