Why does Microsoft advise against readonly fields with mutable values?

前端 未结 7 903
予麋鹿
予麋鹿 2020-12-28 12:34

In the Design Guidelines for Developing Class Libraries, Microsoft say:

Do not assign instances of mutable types to read-only fields.

7条回答
  •  旧巷少年郎
    2020-12-28 13:05

    This is legal in C# (simple Console App)

    readonly static object[] x = new object[2] { true, false };
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            x[0] = false;
            x[1] = true;
    
            Console.WriteLine("{0} {1}", x[0], x[1]); //prints "false true"
            Console.ReadLine();
        }
    

    that would work. but that wouldn't make sense. bear in mind the variable x is readonly, and has not changed (i.e. the ref of x has not changed indeed). but that's not what we meant when we said "readonly x", is it? so don't use readonly fields with mutable values. It's confusing and counter-intuitive.

提交回复
热议问题