C# getter vs readonly

前端 未结 9 2190
遥遥无期
遥遥无期 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:06

    Yes, there's a difference between the two.

    A readonly field can only be set in the constructor.

    A {get; private set;} or just {get;} (for short), can be set at anytime from within the class.

    Example:

    public class Car
    {
        public readonly string Name;
    
        public string color {get; private set;}
    
        public Car()
        {
            Name = "Car";
            Color = "Red";
        }
    
        // will fail compilation
        public void ModifyName()
        {
            Name = "Subaru"
        }
    
        // perfectly ok
        public void ModifyColor()
        {
            Color = "Green"
        }
    }
    

提交回复
热议问题