c# - n 中至多有一个字段不为空

标签 c# algorithm boolean-logic

我在一个类中有 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/

相关文章:

c# - 执行时 ASP.Net MVC "Could Not Load Type"

python - 不同连续子数组的数量

algorithm - 体积内的对象

python - 如何使使用 for 循环的 python 代码运行得更快?

boolean-logic - (正)标准形式的 XOR 子句

java - Java中的 boolean 逻辑表达式

c# - 使用系统数据源而不是用户数据源作为 ODBC 连接字符串

c# - 在 C# 应用程序中安全存储 Azure Blob 存储访问 key 的正确方法

c# - 避免在泛型方法中进行过多的类型检查?

algorithm - 有没有多级逻辑最小化的算法?