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

标签 c# wcf constructor

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

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

    public Item() {}

    public Item(string description)
    {
        this.description = description;
    }
}

之所以有人告诉我,是因为这允许使用 setter 构造对象。但是,我发现 Item 是这样定义的:

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

    public Item(string description)
    {
        this.description = description;
    }
}

可以在不调用构造函数的情况下构造,当通过 WCF 服务引用作为代理类可用时:

Item item = new Item {description = "Some description"};

问题:

  1. 我在声明 new 之后写的代码块到底是什么 项目
  2. [DataContract] 类是否需要空白构造函数?如果是这样,这个空白构造函数的作用是什么?

我发现如果类不是代理类,我无法在没有构造函数的情况下创建对象。

最佳答案

What exactly is that block of code I'm writing

Item item = new Item {description = "Some description"};

相等并被编译为:

Item item = new Item();
item.description = "Some description";

所以它需要一个无参数的构造函数。如果类没有一个,但有一个参数化的,你必须使用那个:

Item item = new Item("Some description");

使用命名参数,它看起来像这样:

Item item = new Item(description: "Some description");

您仍然可以将其与对象初始化语法结合起来:

var item = new Item("Some description")
{
    Foo = "bar"
};

Is a blank constructor required for [DataContract] classes?

是的。默认序列化程序 DataContractSerializer,doesn't use reflection to instantiate a new instance , but still requires a parameterless constructor .

如果找不到无参数构造函数,则无法实例化对象。好吧,它可以,但事实并非如此。因此,如果您要在服务操作中实际使用此 Item 类:

public void SomeOperation(Item item)
{
}

一旦您从客户端调用此操作,WCF 将抛出异常,因为序列化程序无法在 Item 上找到无参数构造函数。

关于c# - WCF [DataContract] 类是否需要空白构造函数?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976947/

相关文章:

c++ - 通过基类 'create' 方法仅将对象创建为共享指针

c# - RightToLeft 标志和原子组

c# - 生成仅具有选定属性的对象概览

c# - 如何将泛型类型参数传递给 lambda 表达式?

.net - WCF - IDuplexSessionRouter VS IRequestReplyRouter

wcf - WCF 上的 REST 服务的 WebInvoke 方法 =“POST” 或 "GET"

c++ - 为什么在声明对象时既不执行构造函数也不执行赋值运算符?

c# - 返回从未使用过的对象的构造函数是否浪费?

c# - 当我在表单 onsubmit 中有函数时,Ajax 不起作用

c# - 无法在 WCF 中序列化字节数组