Why does C# disallow readonly local variables?

后端 未结 13 1237
萌比男神i
萌比男神i 2020-11-27 17:17

Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?

13条回答
  •  Happy的楠姐
    2020-11-27 17:52

    I know, this doesn't answer the why to your question. Anyway, those reading this question might appreciate the code below nonetheless.

    If you are really concerned with shooting your self in the foot when overriding a local variable that should only be set once, and you don't want to make it a more globally accessible variable, you could do something like this.

        public class ReadOnly
        {
            public T Value { get; private set; }
    
            public ReadOnly(T pValue)
            {
                Value = pValue;
            }
    
            public static bool operator ==(ReadOnly pReadOnlyT, T pT)
            {
                if (object.ReferenceEquals(pReadOnlyT, null))
                {
                    return object.ReferenceEquals(pT, null);
                }
                return (pReadOnlyT.Value.Equals(pT));
            }
    
            public static bool operator !=(ReadOnly pReadOnlyT, T pT)
            {
                return !(pReadOnlyT == pT);
            }
        }
    

    Example usage:

            var rInt = new ReadOnly(5);
            if (rInt == 5)
            {
                //Int is 5 indeed
            }
            var copyValueOfInt = rInt.Value;
            //rInt.Value = 6; //Doesn't compile, setter is private
    

    Maybe not as less code as rvar rInt = 5 but it works.

提交回复
热议问题