POCO可以包含构造函数吗?

时间:2014-07-04 04:30:23

标签: c# poco

POCO可以包含构造函数吗?你能告诉我这门课是否正确吗?我还读到POCO必须有一个无参数构造函数。这是正确的,为什么?如果我接受这个无参数构造函数,我的只读Id属性会出现问题。对我来说,似乎合乎逻辑的是,如果此属性必须是只读的,那么初始化它的唯一方法是在构造函数中。

[DataContract]
public class MembershipUser
{
    public MembershipUser(Guid idValue)
    {
        this.Id = idValue;
    }

    [DataMember]
    public virtual readonly Guid Id { get; set; }

    [DataMember]
    public virtual string UserName { get; set; }

    [DataMember]
    public virtual string Email { get; set; }
}

1 个答案:

答案 0 :(得分:2)

POCO对象可以包含其他构造函数,但反序列化需要默认构造函数,因为该进程尝试创建对象的默认实例,然后设置属性。

经过一些研究后,似乎datacontract序列化程序不使用甚至调用默认构造函数。使用此功能,您可以排除默认ctor并仍然序列化您的POCO。您是否应该是您和您的团队必须决定的实施细节。

DataContractSerializer测试:

[Test]
public void SerializerTest()
{
    var s = new SerializeMe(2);
    s.Name = "Test";
    DataContractSerializer dcs = new DataContractSerializer(typeof(SerializeMe));
    Stream ms = new MemoryStream();
    var writer = XmlWriter.Create(ms);
    Assert.DoesNotThrow(() => dcs.WriteObject(writer, s));
    writer.Close();

    ms.Position = 0;
    var reader = new StreamReader(ms);
    var xml = reader.ReadToEnd();
    Console.WriteLine(xml);
}

[Test]
public void DeserializeTest()
{
    var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><SerializeMe xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/Test\"><Id>2</Id><Name>Test</Name></SerializeMe>";
    DataContractSerializer dcs = new DataContractSerializer(typeof(SerializeMe));            
    XmlReader reader = XmlReader.Create(new StringReader(xml));
    var obj = dcs.ReadObject(reader) as SerializeMe;
    Assert.AreEqual(obj.Name, "Test");
}

[DataContract]
public class SerializeMe
{
    public SerializeMe(int id)
    {
        this.Id = id;
    }
    [DataMember]
    public int Id { get; private set; }
    [DataMember]
    public string Name { get; set; }
}