IDataObject.GetData () always returns null with my class

I have a class that I labeled [Serializable] that I am trying to copy over the clipboard. GetData () always returns null.

Copy code:

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

      

Paste the code:

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

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

      

MyClass is actually a derived class. Both he and his base are marked as [Serializable]. I tried the same code with a simple test class and it worked.

MyClass contains GraphicsPath, Pen, Brush, and value type arrays.

+3


source to share


2 answers


The Pen class is not marked serializable and also inherits from MarshalByRefObject.

You will need to implement ISerializable and handle these types of objects



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

      

+3


source


I had the same problem that I googled to find this link This gives you the IsSerializable function to check which part of my class is not serializable. Using this function, I found the chunks that [Serializable] used to make them serializable. Please note that all structures and classes defined within any module (for example, a common one) that the serialized class must use must be marked as [Serializable]. Some of the code cannot / should not be serialized and they must be specially marked as [NonSerialized]. Example: System.Data.OleDBConnection



0


source







All Articles