我在一个类中有 n 个字段。最多允许设置其中一个,因此如果不是这种情况,我需要抛出异常。我知道 n 的值。
我可以用显而易见的方式做到这一点:
if (field1 != null && (field2 != null || field3 != null ||...)
|| field2 != null && (field1 != null || field3 != null ||...)
...)
throw new Exception();
然而,它的长度在字段数中是 n^2,我绝对不想把它写出来,例如。 10 个字段。
我看到过建议通过反射(reflection)来做到这一点的建议。然而,虽然在您不知道 n 的值的情况下这是必要的,但我不禁认为这里必须有更简单的方法。
那么有没有一种方法可以检查 n 个值中是否最多有一个不为空,同时只访问每个值一次?
最佳答案
您可以有一个计数器来计算设置了多少字段。
int numberOfSetFields = 0;
if (field1 != null)
numberOfSetFields++;
if (field2 != null)
numberOfSetFields++;
if (field3 != null)
numberOfSetFields++;
...
if (numberOfSetFields > 1)
{
throw new Exception();
}
或者,如果已经设置至少超过 1 个,您可以使用属性以便不再检查其他字段
int numberOfSetFields = 0;
int NumberOfSetFields
{
get { return numberOfSetFields; }
set
{
numberOfSetFields = value;
if (numberOfSetFields > 1)
throw new Exception();
}
}
if (field1 != null)
NumberOfSetFields++;
if (field2 != null)
NumberOfSetFields++;
if (field3 != null)
NumberOfSetFields++;
...
NumberOfSetFields 属性的设置方法将检查是否至少有 1 个设置字段。这样,如果假设您有 10 个字段,并且设置了前 2 个,那么与我提到的第一种方法相比,将不再检查其他 8 个。
关于c# - n 中至多有一个字段不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621484/