IDataObject.GetData()在我的类中总是返回null
本文关键字:返回 null 我的 GetData IDataObject | 更新日期: 2023-09-27 18:27:16
我有一个标记为[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和值类型的数组。
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
}
我遇到了同样的问题,然后我在谷歌上搜索找到了这个链接它为您提供了一个函数IsSerializable来测试我的类的哪一部分是不可序列化的。通过使用此函数,我发现这些部分使用[Serializable]使其可序列化。请注意,要序列化的类使用的任何模块(如general)内定义的所有结构和类都必须标记为[Serializable]。代码的某些部分不能/不应该序列化,它们应该特别标记为[NonSerialized]。例如:System.Data.OleDBConnection