gpt4 book ai didi

c# - C# 中的只读属性与只读成员变量

转载 作者:行者123 更新时间:2023-11-30 13:59:51 24 4
gpt4 key购买 nike

我有一个类ExProperty,如下所示:

class ExProperty
{
private int m_asimplevar;
private readonly int _s=2;

public ExProperty(int iTemp)
{
m_asimplevar = iTemp;
}

public void Asimplemethod()
{
System.Console.WriteLine(m_asimplevar);
}

public int Property
{
get {return m_asimplevar ;}
//since there is no set, this property is just made readonly.
}
}

class Program
{
static void Main(string[] args)
{
var ap = new ExProperty(2);
Console.WriteLine(ap.Property);
}
}
  1. 制作/使用只读或只写属性的唯一目的是什么?我看到,通过下面的程序,readonly达到了同样的目的!

  2. 当我将属性设置为只读时,我认为它不应该是可写的。当我使用

    public void Asimplemethod()
    {
    _s=3; //Compiler reports as "Read only field cannot be used as assignment"
    System.Console.WriteLine(m_asimplevar);
    }

    是的,没关系。

    但是,如果我使用

    public ExProperty(int iTemp)
    {
    _s = 3 ; //compiler reports no error. May be read-only does not apply to constructors functions ?
    }

    为什么编译器在这种情况下不报错?

  3. 声明 _s=3 可以吗?还是应该声明 _s 并使用构造函数为其赋值?

最佳答案

是的,readonly 关键字意味着该字段只能在字段初始值设定项和构造函数中写入。

如果需要,您可以将 readonly 与属性方法结合使用。属性的 private 支持字段可以声明为 readonly 而属性本身只有一个 getter。然后支持字段只能在构造函数中分配给(及其可能的字段初始值设定项)。

您可以考虑的另一件事是创建一个 public readonly 字段。由于字段本身是只读的,如果 getter 所做的只是返回字段值,那么实际上您不会从中获得太多。

关于c# - C# 中的只读属性与只读成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com