2012-03-29 116 views
-1

對象我創建了一個擴展方法,將告訴我的每一個對象的大小創建 這樣的: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,不是所有的對象將是能夠回答答案,只有可串聯的答案。有沒有辦法將此方法附加到可以序列化的對象?

回答

0

您可以使用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; 
      }   
    } 
+0

嗨,感謝您的快速反應,我有幾種方法來防止異常(也與try/catch)。我希望防止擴展方法出現在編譯時不可序列化的對象中 – user1166664 2012-03-29 16:10:16

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; 
    } 
}