我试图在 silverligth 5 中创建对象的副本,其中IFormatters和IcCloanble等接口不支持。 *
我的对象是这样的:(注意这些obkjects是在反序列化xml时获得的): 我试着像这样复制:
[XmlRoot(ElementName = "component")]
public class Component
{
[XmlElement("attributes")]
public Attributes Attributes { get; set; }
[XmlIgnore]
public Attributes atrbtOrginal = new Attributes();
[XmlIgnore]
public Attributes atrbtCopy{ get; set; }
}
public Component()
{
atrbtCopy= atrbtOrginal ;
}
当然,我在Google上搜索此代码时无法正常工作:
public static class ObjectCopier
{
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
And i thought of doing something liek this:
objectOrginal.Clone();.
但是silverligth5中的问题是:
Error 2 The type or namespace name 'BinaryFormatter' could not be found (are you missing a using directive or an assembly reference?)
Error 1 The type or namespace name 'IFormatter' could not be found (are you missing a using directive or an assembly reference?)
Silverlight 5中是否有其他选择。请详细解释。 非常感谢。
答案 0 :(得分:1)
在类上实现DataContractSerializer属性(DataContract,DataMember)并调用DatacontractSerializer将其序列化为MemoryStream,然后再次使用它将MemoryStream序列化为对象的新实例。到目前为止最容易理解,也非常高效。
类定义示例:
[DataContract]
class MyClass
{
[DataMember]
public int MyValue {get;set;}
[DataMember]
public string MyOtherValue {get;set;}
}
Microsoft文档http://msdn.microsoft.com/en-us/library/ms752244(v=vs.110).aspx
中介绍了从一个类实例克隆到另一个类实例的方法