我有一堂课就像
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) { /* ... */ }
但这并不影响我的追求。