【问题标题】:C# variable that can't be changed but need to be initialed in the constructor无法更改但需要在构造函数中初始化的 C# 变量
【发布时间】:2015-12-22 08:52:33
【问题描述】:

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

类似这样的:

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 而不是 const - const 用于编译时常量。

标签: c# constructor constants final


【解决方案1】:

这正是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
}

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

【讨论】:

  • 谢谢。我不在我的 IDE 中,所以我只是复制并粘贴了他的构造函数。当然,这是假设 strienter 和 hereng 是实际定义的类型
  • @HosseinNarimaniRad "For an instance field, in the instance constructors of the class that contains the field declaration",所以它们可以同时存在,只要它们不是静态的。由于问题是关于在构造函数中设置,只读不应该是静态的。
  • @Trisped 是的,我在 IDE 中快速键入代码,并没有注意到我将该字段标记为只读和静态。
【解决方案2】:

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

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

readonly (C# Reference):

您只能在以下情况下为只读字段赋值 上下文:

  • 在声明中初始化变量时。
  • 对于实例字段,在包含字段声明的类的实例构造函数中,或者对于静态字段,在 包含字段声明的类的静态构造函数。 这些也是唯一可以通过 readonly 字段作为 out 或 ref 参数。

如果您希望值不能从您的类中被触及,您可以在属性中使用私有设置器:

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

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

【讨论】:

  • MyProperty 也可以在属于 Class1 的任何其他方法中设置,而不仅仅是在 Class1 的构造函数中。
  • 您需要为您复制的内容添加引用。
  • @Trisped 参考已添加。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 2014-05-19
    • 1970-01-01
    • 2020-09-27
    • 2015-02-19
    • 2011-03-18
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多