给出以下代码:
public struct Foo
{
public Foo(int bar, int baz) : this()
{
Bar = bar; // Err 1, 2
Baz = baz; // Err 3
}
public int Bar { get; private set; }
public int Baz { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
什么是: this()真正做到?没有默认构造函数,所以它调用了什么?没有这个附录,整个事情就会因错误而崩溃.
Error 1 The 'this' object cannot be used before all of its fields are assigned to Error 2 Backing field for automatically implemented property 'Foo.Bar' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Error 3 Backing field for automatically implemented property 'Foo.Baz' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
Geo*_*uer 14
那么为什么在C#中不允许没有参数的结构构造函数呢?这是因为结构已经包含一个没有参数的默认构造函数.请记住,此默认构造函数是.Net框架的一部分,因此在我们的代码中不可见.默认构造函数的唯一目的是为其成员分配默认值.
基本上,所有结构都已经有一个默认构造函数.一个班级的情况会有所不同.
在使用属性快捷方式时,只能通过其setter和getter访问属性.但是,在分配所有字段之前,不允许您呼叫任何设置者.解决方法是调用自动创建的无参数构造函数,初始化字段.这当然意味着您要两次初始化字段.
几天前,当我遇到这个问题时,我刚刚删除了属性的快捷方式,并自己声明了局部变量,以便我可以在构造函数中设置它们:
public struct Foo {
public Foo(int bar, int baz) {
_bar = bar;
_baz = baz;
}
private int _bar, _baz;
public int Bar { get { return _bar; } }
public int Baz { get { return _baz; } }
}
Run Code Online (Sandbox Code Playgroud)