需要帮助才能理解c#语句

时间:2011-10-16 18:23:34

标签: c#

您需要帮助理解以下陈述及其所做的逻辑。

AuthenticationProvider auth = 
    (level & Levels.Authentication) == Levels.Authentication
        ? GetAuthenticationProviderByName(authentication, authPhrase)
        : DefaultAuthenticationProvider.Instance;

我看到我正在制作一个AuthentcationProvider,但后来我不明白发生了什么,为什么会有比较,问题是什么?

感谢。

5 个答案:

答案 0 :(得分:2)

这里的?:称为conditional operator(有时也称为三元运算符)。

您发布的代码与此相同:

AuthenticationProvider auth;
if ((level & Levels.Authentication) == Levels.Authentication) { 
    auth = GetAuthenticationProviderByName(authentication, authPhrase);
} else {
    auth = DefaultAuthenticationProvider.Instance;
}

&是“按位和”。这里用它来测试是否设置了Levels.Authentication位。

答案 1 :(得分:1)

这是Ternary operator

condition ? first_expression : second_expression;

就像if...else的简短版本一样。

答案 2 :(得分:1)

看起来它正在进行级别和级别之间的逐位比较。身份验证。我假设level是一个“flags”变量,它正在检查Levels.Authentication标志是否打开。

如果是这样,它会执行GetAuthenticationByName,否则它会执行DefaultAuthenticationProvider.Instance。

答案 3 :(得分:1)

level是Levels类型的变量,是用enum装饰的FlagsAttribute

这意味着您可以在一个变量中组合该枚举的多个值。

level & LevelsAuthentication == Levels.Authentication行检查关卡变量是否设置了值Levels.Authentication

如果是,则执行GetAuthenticationProviderByName(authentication, authPrase)语句。 如果为false,则返回D efaultAuthenticationProvider.Instance

有关详细信息,请查看:

答案 4 :(得分:0)

是条件运算符,请参见此处:?: Operator (C# Reference)

它的工作原理如下:

s = x != 0.0 ? Math.Sin(x)/x : 1.0;

仅在Math.Sin(x)/x

时才分配给x != 0