2

C# 中是否存在基本成员初始化部分?我尝试搜索和搜索,但不断提出有关初始化List 类的问题。我所指的初始化列表类似于此处的示例。

这样做的一个原因是初始化一个类中的常量。我基本上是想弄清楚我是否可以执行以下操作:

public class A{
    private const string _name;
    public A(string name): _name(name){
         //stuff
    }
}

同样,我试图在 C# 中执行此操作,而不是 C++。有什么想法吗?

4

2 回答 2

4

您可以使用在构造函数中初始化的私有只读字段来执行此操作,因此:

public class A 
{
    private readonly string _name;

    public A (string name)
    {
        _name = name;
    }
}

一个readonly字段只能内联或在构造函数中初始化,然后是常量。

于 2012-11-24T06:05:46.257 回答
3

No, C# does not support member initialization before constructor body the same way as C++ does. You can either initialize fields when they are declared or using normal assignament inside contructor body.

The only 2 methods can be used at that position - call to contructor of base class and call to another contructor in the same class. You can check C# specification (i.e. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf, section 17.10 Instance constructors) for details:

constructor-declaration:
    attributesopt constructor-modifiersopt constructor-declarator constructor-body

constructor-declarator:
   identifier ( formal-parameter-listopt ) constructor-initializer
constructor-initializer:
  : base ( argument-listopt )
  : this ( argument-listopt )
于 2012-11-24T06:12:45.087 回答