2

IFormatters や IcCloanble などのインターフェイスがサポートされていない Silverlight 5でオブジェクトのコピーを作成しようとしていました。*

私のオブジェクトは次のようなものです: (これらのオブジェクトは 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 に代替手段はありますか。詳しく説明してください。どうもありがとう。

4

1 に答える 1

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で説明されています。

于 2014-08-18T09:14:36.050 に答える