【问题标题】:IDataObject.GetData() always returns null with my classIDataObject.GetData() 总是在我的班级中返回 null
【发布时间】:2012-03-26 07:59:47
【问题描述】:

我有一个标记为 [Serializable] 的类,我正试图通过剪贴板进行复制。调用 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 和值类型数组。

【问题讨论】:

    标签: c# clipboard serializable idataobject


    【解决方案1】:

    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
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,然后我用谷歌搜索找到this 链接 它为您提供了一个函数 IsSerializable 来测试我的类的哪个部分不可序列化。通过使用这个函数,我发现这些部分使用 [Serializable] 使它们可序列化。请注意,在要序列化的类使用的任何模块(如通用模块)内定义的所有结构和类都必须标记为 [Serializable]。代码的某些部分不能/不应该被序列化,它们应该被专门标记为 [NonSerialized]。例如:System.Data.OleDBConnection

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 2015-12-03
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多