What is the difference between const and readonly in C#?

前端 未结 30 3268
挽巷
挽巷 2020-11-22 05:05

What is the difference between const and readonly in C#?

When would you use one over the other?

30条回答
  •  暖寄归人
    2020-11-22 05:26

    Yet another gotcha: readonly values can be changed by "devious" code via reflection.

    var fi = this.GetType()
                 .BaseType
                 .GetField("_someField", 
                           BindingFlags.Instance | BindingFlags.NonPublic);
    fi.SetValue(this, 1);
    

    Can I change a private readonly inherited field in C# using reflection?

提交回复
热议问题