我试图在创建对象的副本 silverligth 5 其中像IFormatters和IcCloanble接口不支持。 *
I was trying to create copy of objects in silverligth 5 where interfaces like IFormatters and IcCloanble do not support. *
我的对象是这样的:(请注意,这些obkjects是在反序列化XML获得): 我试图做复制这样的:
My objects are like this: (Note that these obkjects are obtained on deserializing xml): I tried to do copy like this:
[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 ;
}
当然它不会工作,然后我得到这个code对seraching对谷歌:
Sure it will not work then i got this code on seraching on 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问题是:
But the problem in silverligth5 is :
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的任何选择。请详细解释一下。 非常感谢。
is there any alternative in Silverlight 5 . Please explain in detail. Thanks a lot.
实施DataContractSerializer的属性(DataContract,数据成员)在你的类和调用的DataContractSerializer将其序列化到一个MemoryStream,然后再次用它来序列化出的MemoryStream来该对象的新实例。到目前为止,最容易理解,而且相当高性能的了。
Implement the DataContractSerializer attributes (DataContract, DataMember) on your classes and call DatacontractSerializer to serialize it to a MemoryStream, then use it again to serialize out of the MemoryStream to a new instance of the object. By far the easiest to understand, and quite performant too.
类定义的例子:
[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
上一篇:ASP.NET MVC应用程序提供了在Firefox中看到,只有当内部服务器错误应用程序、错误、服务器、NET
下一篇:Dispatcher.BeginInvoke不被在一种情况下执行的不被、情况下、Dispatcher、BeginInvoke