如何告诉VS成员不为空

问题描述 投票:0回答:0

我有一堂课就像

    class Operation
    {
        private int? opA = null;
        private int? opB = null;
        private Func<int>? opFunc = null;

        public void SetOperandA(int value)
            => opA = value;
        public void SetOperandB(int value)
            => opB = value;

        public void SetAdd()
            => SetOperator(() => (int)opA + (int)opB);
        public void SetSubtract()
            => SetOperator(() => (int)opA - (int)opB);

        public void SetOperator(Func<int> op)
        {
            if (opA is null || opB is null)
                throw new Exception("Both operands must be set first!");
            opFunc = op;
        }

        public int Evaluate()
        {
            if (opFunc is null)
                throw new Exception("Operator must be set first!");
            return opFunc();
        }
    }

问题是在

SetAdd()
函数中,VS抱怨
SetOperator(() => (int)opA + (int)opB);
行说
opA
opB
可能是
null
,即使他们永远不应该是
null
如何
SetOperator()
作品。

我在努力告诉VS,好像我在做

        public void SetMultiply()
        {
            if (opA is null || opB is null)
                throw new Exception("Both operands must be set first!");

            opFunc = () => (int)opA * (int)opB;
        }

VS 能够推断出在

opFunc = () => (int)opA * (int)opB;
线上,
opA
opB
都不是
null
并且没有潜在的问题。

我试过添加

        [MemberNotNull(nameof(opA))]
        [MemberNotNull(nameof(opB))]
        private void SetOperator(Func<int> op) { /* ... */ }

但这并不影响我的追求。

c# visual-studio nullable
© www.soinside.com 2019 - 2024. All rights reserved.