Skip to main content
 首页 » 编程设计

c#之DataObject.GetData() 无论如何都会返回 MemoryStream 类型的对象

2024年02月13日21qq号

我不知道为什么 GetData() 方法需要一个 Type 的参数,我认为 Type 是指定对象应该是哪个类/类型的。 我有一个名为 GraphicsPathWrap 的结构,通过实现 ISerializable 使其可序列化。我尝试了以下复制功能:

private void Copy(GraphicsPathWrap gpw){ 
  DataObject obj = new DataObject(); 
  obj.SetData(typeof(GraphicsPathWrap), gpw); 
  Clipboard.SetDataObject(obj); 
} 

然后尝试了下面的粘贴功能:

private GraphicsPathWrap Paste() 
{ 
  return (GraphicsPathWrap)Clipboard.GetDataObject().GetData(typeof   (GraphicsPathWrap)); 
} 

它应该可以工作,但是 GetData(...) 返回一个类型为 MemoryStream 的对象并且抛出了一个 InvalidCastException。我不明白为什么它是 MemoryStream 的类型。我认为它应该可以转换为 GraphicsPathWrap? 我可以通过使用 BinaryFormatter 反序列化 MemoryStream 来解决这个问题,但是当剪贴板不能为我做所有事情时,这太荒谬了吗?

谢谢!

请您参考如下方法:

编辑:我已经完全模拟了你的情况,当你实现了 ISerializable 接口(interface)并且没有正确反序列化时,它正在说 MemoryStream。

GetData() 在以下场景中返回内存流:

      [Serializable] 
        public struct GraphicsPathWrap : ISerializable 
        { 
            private static string myValue = "This is the value of the class";              
 
            // Creates a property to retrieve or set the value.  
            public string MyObjectValue 
            { 
                get 
                { 
                    return myValue; 
                } 
                set 
                { 
                    myValue = value; 
                } 
            } 
 
            #region ISerializable Members 
 
            public void GetObjectData(SerializationInfo info, StreamingContext context) 
            { 
 
            } 
 
            #endregion 
        }  

然后,当 GetData() 给出正确的类型对象时,我正确地实现了序列化\反序列化

[Serializable] 
        public struct GraphicsPathWrap : ISerializable 
        { 
            private static string myValue = "This is the value of the class"; 
 
            public GraphicsPathWrap(SerializationInfo info, StreamingContext ctxt)  // Deserialization Constructor 
            { 
                myValue = (string)info.GetValue("MyValue", typeof(string)); 
            } 
 
            // Creates a property to retrieve or set the value.  
            public string MyObjectValue 
            { 
                get 
                { 
                    return myValue; 
                } 
                set 
                { 
                    myValue = value; 
                } 
            } 
 
            #region ISerializable Members 
 
            public void GetObjectData(SerializationInfo info, StreamingContext context) 
            { 
                info.AddValue("MyValue", myValue); // Serialize the value 
            } 
 
            #endregion 
        } 

希望以上回答对您有所帮助