2012-03-08 118 views
3

我有一個類,我標記爲[Serializable],我試圖通過剪貼板複製。調用GetData()總是返回null。IDataObject.GetData()總是返回null與我的類

複製代碼:

IDataObject dataObject = new DataObject(); 
dataObject.SetData("MyClass", false, myObject); 
Clipboard.SetDataObject(dataObject, true); 

粘貼代碼:

if (Clipboard.ContainsData("MyClass")) 
{ 
    IDataObject dataObject = Clipboard.GetDataObject(); 

    if (dataObject.GetDataPresent("MyClass")) 
    { 
     MyClass myObject = (MyClass)dataObject.GetData("MyClass"); 
     // myObject is null 
    } 
} 

MyClass的實際上是一個派生類。它和它的基地都被標記爲[Serializable]。我嘗試了一個簡單的測試類相同的代碼,它的工作。

MyClass包含GraphicsPath,Pen,Brush和值數組類型。

回答

3

Pen類未標記爲可序列化,並且還從MarshalByRefObject繼承。

您需要實現了ISerializable和處理這些類型的對象

[Serializable] 
public class MyClass : ISerializable 
{ 
    public Pen Pen; 

    public MyClass() 
    { 
     this.Pen = new Pen(Brushes.Azure); 
    } 

    #region ISerializable Implemention 

    private const string ColorField = "ColorField"; 

    private MyClass(SerializationInfo info, StreamingContext context) 
    { 
     if (info == null) 
      throw new ArgumentNullException("info"); 

     SerializationInfoEnumerator enumerator = info.GetEnumerator(); 
     bool foundColor = false; 
     Color serializedColor = default(Color); 

     while (enumerator.MoveNext()) 
     { 
      switch (enumerator.Name) 
      { 
       case ColorField: 
        foundColor = true; 
        serializedColor = (Color) enumerator.Value; 
        break; 

       default: 
        // Ignore anything else... forwards compatibility 
        break; 
      } 
     } 

     if (!foundColor) 
      throw new SerializationException("Missing Color serializable member"); 

     this.Pen = new Pen(serializedColor); 
    } 

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     info.AddValue(ColorField, this.Pen.Color); 
    } 
    #endregion 
} 
0

我有同樣的問題,那麼我用Google搜索找到this鏈接 它給你一個功能IsSerializable,以測試其班上的部分是不可序列化。通過使用這個函數,我發現了那些使用[Serializable]來使它們可序列化的部分。請注意,在要序列化的類所使用的任何模塊(如常規)內定義的所有結構和類必須標記爲[可序列化]。代碼的某些部分不能/不應該被序列化,並且應該特別標記爲[NonSerialized]。例如:System.Data.OleDBConnection