3

我有一个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使用构造函数声明并分配它的值?

4

2 回答 2

5

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

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

您可以考虑的另一件事是制作一个字段。由于字段本身是只读的,因此如果 getter 所做的只是返回字段值,那么实际上您并没有从 getter 中获得什么。public readonly

于 2012-09-18T06:24:26.317 回答
3

属性的关键是为类外部提供接口。通过不定义Set或将其设为私有,您可以将其设置为在类外部“只读”,但仍然可以从类方法内部对其进行更改。

By making field readonly, you are saying it should never change, no matter from where this change comes.

于 2012-09-18T06:27:56.607 回答