如何只在wcf中序列化一个具有复杂属性的对象一次?

时间:2014-10-15 17:30:10

标签: c# .net wcf

我想序列化一个名为ComplexModel的对象,该对象在wcf中具有复杂属性,首先我使用List<SimpleModel> SimpleModel作为我对象的属性。

我的wcf模型

  [DataContract]
//[KnownType(typeof(SimpleModel[]))]
public class ComplexModel
{
    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public Int32 Age { get; set; }

    //change List<SimpleModel> to SimpleModelCollection
    [DataMember]
    public SimpleModelCollection SimpleModel { get; set; }
}

/// <summary>
///  defined a custom type to implement the IEnumerable interface instead of List SimpleModel
/// </summary>
[Serializable]
[CollectionDataContract]
[KnownType(typeof (SimpleModel))]
public class SimpleModelCollection : IEnumerable<SimpleModel>
{
    public IList<SimpleModel> List = new List<SimpleModel>();

    public SimpleModelCollection()
    {
    }

    public SimpleModelCollection(IList<SimpleModel> objs)
    {
        List = objs;
    }

    public void Add(SimpleModel obj)
    {
        List.Add(obj);
    }

    //IEnumerable<SimpleModel> member
    public IEnumerator<SimpleModel> GetEnumerator()
    {
        return List.GetEnumerator();
    }

    //IEnumerable member
    IEnumerator IEnumerable.GetEnumerator()
    {
        return List.GetEnumerator();
    }
}

[DataContract]
public class SimpleModel
{
    [DataMember]
    public string MumName { get; set; }

    [DataMember]
    public int Point { get; set; }

    [DataMember]
    public DateTime BirthDate { get; set; }
}

我调试它告诉我我没有实现IEnumerable接口。所以我尝试实现它,但它仍然告诉我实现IEnumerable接口。如果我有其他复杂属性,我必须定义另一个集合。有没有更好的方法来避免这种情况?为什么为什么最好直接返回xml或json格式而不是对象(实体)?

我的wcf界面

 [ServiceContract]
public interface ITestService1
{
    [OperationContract]
    ComplexModel DoWork();
}

我的wcf课程

public class TestService1 : ITestService1
{
    public ComplexModel DoWork()
    {
        var SimpleModels = new SimpleModelCollection();
        SimpleModels.Add(new SimpleModel
        {
            MumName = "def",
            BirthDate = DateTime.MinValue,
            Point = 99
        });
        SimpleModels.Add(new SimpleModel
        {
            MumName = "hig",
            BirthDate = DateTime.Now,
            Point = 100
        });
        return new ComplexModel
        {
            Age = 10,
            Name = "abc",
            SimpleModel = SimpleModels
        };
    }
}

0 个答案:

没有答案
相关问题