在接口中定义序列化的DataMember,然后在实现该接口的类中使用它。

5

基本上,当返回一个YoyoData类型的对象时,下面的代码是否应该起作用并序列化string Yoyo

    public interface IHelloV1
    {
        #region Instance Properties

        [DataMember(Name = "Yoyo")]
        string Yoyo { get; set; }

        #endregion
    }


    [DataContract(Name = "YoyoData", Namespace = "http://hello.com/1/IHelloV1")]
    public class YoyoData : IHelloV1
    {
        string Yoyo { get; set; }

        public YoyoData()
        {
            Yoyo = "whatever";
        }
    }
}

似乎是职责混淆的好奇组合。 - H H
@Henk - 这是由代码继承强制实施的,我只是想知道它是否会起作用;-) - Matt
2个回答

6

我认为不会。

DataMember属性在派生类中不会被继承。

更多详情请参阅类型DataMemberAttribute的文档以及它是如何定义的:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx。 该属性指定Inherited = false,这意味着该属性不会传递到派生类。

此外,有关属性上的Inherited属性的更多详细信息,请参见http://msdn.microsoft.com/en-us/library/84c42s56(v=vs.71).aspx

总之,这意味着在定义DataContract的类中,属性Yoyo不会被视为DataMember,所以对我来说它将无法按预期工作。


我的测试证实了这一点。我只是好奇是否错过了什么步骤,但你说的很有道理。谢谢! - Matt

3
似乎它无法正常工作
using System.Runtime.Serialization;
using System.IO;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            IHelloV1 yoyoData = new YoyoData();
            var serializer = new DataContractSerializer(typeof(YoyoData));

            byte[] bytes;
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, yoyoData);
                stream.Flush();
                bytes = stream.ToArray();
            }

            IHelloV1 deserialized;
            using (var stream = new MemoryStream(bytes))
            {
                deserialized = serializer.ReadObject(stream) as IHelloV1;
            }

            if (deserialized != null && deserialized.Yoyo == yoyoData.Yoyo)
            {
                Console.WriteLine("It works.");
            }
            else
            {
                Console.WriteLine("It doesn't work.");
            }

            Console.ReadKey();
        }
    }

    public interface IHelloV1
    {
        #region Instance Properties

        [DataMember(Name = "Yoyo")]
        string Yoyo { get; set; }

        #endregion
    }


    [DataContract(Name = "YoyoData", Namespace = "http://hello.com/1/IHelloV1")]
    public class YoyoData : IHelloV1
    {
        public string Yoyo { get; set; }

        public YoyoData()
        {
            Yoyo = "whatever";
        }
    }
}

但是,如果你将该属性放在类属性而不是接口属性上,它就可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接