C# WCF[DataContract]类是否需要空白构造函数?为什么?

C# WCF[DataContract]类是否需要空白构造函数?为什么?,c#,wcf,constructor,C#,Wcf,Constructor,有人告诉我,包含getter和setter的可序列化对象需要一个空构造函数,如下所示: [DataContract] public class Item { [DataMember] public string description { get; set; } public Item() {} public Item(string description) { this.description = description; }

有人告诉我,包含getter和setter的可序列化对象需要一个空构造函数,如下所示:

[DataContract]
public class Item
{
    [DataMember]
    public string description { get; set; }

    public Item() {}

    public Item(string description)
    {
        this.description = description;
    }
}
告诉我的原因是,这允许使用setter构造对象。但是,我发现,当定义如下时:

[DataContract]
public class Item
{
    [DataMember]
    public string description { get; set; }

    public Item(string description)
    {
        this.description = description;
    }
}
Item item = new Item(description: "Some description");
当通过WCF服务引用作为代理类提供时,无需调用构造函数即可构造:

Item item = new Item {description = "Some description"};
问题:

  • 在声明
    new之后,我正在编写的代码块到底是什么
    项目
  • [DataContract]类是否需要空白构造函数?如果是,这个空构造函数做什么
  • 我发现,如果类不是代理类,没有构造函数就无法创建对象

    我正在写的那段代码到底是什么

    等于并编译为:

    Item item = new Item();
    item.description = "Some description";
    
    所以它需要一个无参数构造函数。如果类没有参数化的参数化参数,则必须使用该参数:

    Item item = new Item("Some description");
    
    使用命名参数,它将如下所示:

    [DataContract]
    public class Item
    {
        [DataMember]
        public string description { get; set; }
    
        public Item(string description)
        {
            this.description = description;
        }
    }
    
    Item item = new Item(description: "Some description");
    
    您仍然可以将其与对象初始值设定项语法结合使用:

    var item = new Item("Some description")
    {
        Foo = "bar"
    };
    
    [DataContract]类是否需要空白构造函数

    对。默认序列化程序DataContractSerializer

    如果找不到无参数构造函数,则无法实例化对象。嗯,可以,但是不行。因此,如果您要在服务操作中实际使用此
    类:

    public void SomeOperation(Item item)
    {
    }
    

    然后,一旦您从客户端调用此操作,WCF将引发异常,因为序列化程序在
    项上找不到无参数构造函数

    谢谢。对于通过服务引用使用的服务中的项,我肯定没有无参数构造函数。代理类是用空构造函数自动生成的吗?如果一个类根本不包含构造函数,则会自动生成一个无参数的构造函数(请参见:)。那么我不确定您在问什么。因为,没有构造函数或方法(除非在生成客户机时引用包含数据协定的程序集并选择重用类型,但这是另一种情况)。如果将
    Item
    用作服务操作参数(
    IService1.Foo(Item Item)
    ),则当您调用该操作时,这将在运行时爆发,因为序列化程序在服务端的
    项上找不到无参数构造函数。
    是。序列化程序使用反射实例化新实例,并使用无参数构造函数进行实例化。
    这不是真的。在WCF中使用了一些黑魔法创建对象的实例。另请参见