C# getter vs readonly

前端 未结 9 2170
遥遥无期
遥遥无期 2020-12-29 19:23

Is there any difference between the following?

class C
{
    // One:
    public static readonly int ValueAsAMember = 42;

    // Two:
    public static int V         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 20:05

    There are two major differences:

    The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.

    The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:

    public class MyTestClass
    {
        public readonly int MyInt = 1;
    
        public MyTestClass()
        {
            MyInt = 2;
        }
    }
    

    If a caller does

    new MyTestClass().MyInt
    

    they will get 2. The same goes for static constructors for a static readonly field.

提交回复
热议问题