无法更改但需要在构造函数中初始化的C#变量

C# variable that can't be changed but need to be initialed in the constructor

我需要一个在构造函数中初始化后无法更改的属性

像这样的东西:

private const string banknr;

public ClassName(string banknr)
{
    this.banknr = banknr;
    //from now on "banknr" can't be changed something like a final or const
}

但是就是不行,我真的不懂

这正是 readonly 关键字的作用。

private readonly string banknr;

public ClassName(string banknr)
{
    this.banknr = banknr;
    //from now on "banknr" can't be changed something like a final or const
}

只读变量可以在构造函数中设置,但不能更改。

如果你希望值在初始化后不能被触及,你可以使用readonly关键字:

public class Class2
{
    public readonly string MyProperty;
    public Class2()
    {
        MyProperty = "value";
    }
}

readonly (C# Reference):

You can assign a value to a readonly field only in the following contexts:

  • When the variable is initialized in the declaration.
  • For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.

如果您不想从您的 class 中获取值,您可以在 属性 中使用私有 setter:

public class Class1
{
    public string MyProperty { get; private set; }

    public Class1()
    {
        MyProperty = "value";
    }
}

你想要 readonly 而不是 const。可以在 http://weblogs.asp.net/psteele/63416 处找到差异。总结在这里:

  • const: 仅在声明时初始化
  • 只读:可以在声明或构造函数中初始化