是更好来初始化声明类成员变量
Is it better to initialize class member variables on declaration
private List<Thing> _things = new List<Thing>(); private int _arb = 99;或默认的构造函数?
private List<Thing> _things; private int _arb; public TheClass() { _things = new List<Thing>(); _arb = 99; }这纯粹是一种风格问题还是有性能折衷,一种方式或其他?
Is it simply a matter of style or are there performance trade-offs, one way or the other?
推荐答案在性能方面,没有真正的区别;字段初始被实现为构造逻辑。唯一的区别是,字段初始发生之前任何基地/本构造函数。
In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor.
构造方法可以自动实现属性可以使用(字段初始不能) - 即
The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.
[DefaultValue("")] public string Foo {get;set;} public Bar() { // ctor Foo = ""; }除此之外,我倾向于preFER领域的初始化程序语法;我发现它让事情本地化 - 即
Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized - i.e.
private readonly List<SomeClass> items = new List<SomeClass>(); public List<SomeClass> Items {get {return items;}}我没有去打猎向上和向下找到它被分配...
I don't have to go hunting up and down to find where it is assigned...
最明显的例外是您需要执行复杂的逻辑或处理构造函数的参数 - 在这种情况下,基于构造函数初始化是要走的路。同样,如果你有多个构造函数,这将是preferable的领域总是设置相同的方式 - 所以你可能有这样构造函数:
The obvious exception is where you need to perform complex logic or deal with constructor parameters - in which case constructor-based initialization is the way to go. Likewise, if you have multiple constructors, it would be preferable for the fields to always get set the same way - so you might have ctors like:
public Bar() : this("") {} public Bar(string foo) {Foo = foo;}编辑:作为一个方面的评论,请注意,在上面,如果有其他字段(未显示)与现场初始化,那么他们只能直接调用基地(构造函数初始化.. 。) - 即公开栏(串富)构造函数。其他构造确实的不的运行字段初始,因为它知道他们所做的此(...)男星。
edit: as a side comment, note that in the above, if there are other fields (not shown) with field initializers, then they are only directly initialized in the constructors that call base(...) - i.e. the public Bar(string foo) ctor. The other constructor does not run field initializers, since it knows they are done by the this(...) ctor.
更多推荐
C#成员变量初始化;最佳实践?
发布评论