繁体   English   中英

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

[英]Is there a way to initialize fields out of constructor in C#?

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

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

有线索吗?

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

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

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

这将是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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM