Why are we allowed to use const with reference types if we may only assign null to them?

前端 未结 4 1258
暖寄归人
暖寄归人 2021-01-04 12:08

The question is actually very straightforward. The following code throws the exception right below it:

class Foo
{
    public const StringBuilder BarBuilder          


        
4条回答
  •  借酒劲吻你
    2021-01-04 12:11

    However, I don't see the reason why or where we would use null constant.

    Null constants are useful as sentinel values.

    For example, this:

    public class MyClass
    {
        private const Action AlreadyInvoked = null;
    
        private Action _action;
    
        public MyClass(Action action) {
            _action = action;
        }
    
        public void SomeMethod()
        {
            _action();
    
            _action = AlreadyInvoked;
        }
    
        public void SomeOtherMethod()
        {
            if(action == AlreadyInvoked)
            {
                //...
            }
        }
    }
    

    Is much more expressive than this:

    public class MyClass
    {
        //...
    
        public void SomeMethod()
        {
            _action();
    
            _action = null;
        }
    
        public void SomeOtherMethod()
        {
            if(action == null)
            {
                //...
            }
        }
    }
    

    The source code for the Lazy class shows Microsoft used a similar strategy. Although they used a static readonly delegate that can never be invoked as a sentinel value, they could have just used a null constant instead:

    static readonly Func ALREADY_INVOKED_SENTINEL = delegate
    {
        Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
        return default(T);
    };
    

提交回复
热议问题