有没有办法在C#中用构造函数初始化字段?

时间:2012-05-02 06:09:15

标签: c# constructor

我似乎记得某种简短的方法来初始化发送给构造函数的类的字段,如:

 Class A {
    int n;
    public A(int N) : n(N) {}
 }

任何线索?

2 个答案:

答案 0 :(得分:4)

在构造函数之后有一种简单的方法来初始化类字段:

public class A
  {
    public int N;
    public string S;
    public A() {}
  }

  class B
  {
     void foo()
     {
        A a = new A() { N = 1, S = "string" }
     }
  }

答案 1 :(得分:2)

那将是C ++,但你标记了你的问题C#。 C#没有初始化列表的概念,只需在构造函数中指定字段即可。但是,您可以以类似的方式链接构造函数或调用基类构造函数

// call base class constructor before your own executes
public class B : A
{
    public B(int whatever)
        : base(something)
    {
        // more code here
    }
}

// call secondary constructor
public class B : A
{
    private int _something;

    public B() : this(10) { }

    public B(int whatever)
    {
        _something = whatever;
    }
}