您需要帮助理解以下陈述及其所做的逻辑。
AuthenticationProvider auth =
(level & Levels.Authentication) == Levels.Authentication
? GetAuthenticationProviderByName(authentication, authPhrase)
: DefaultAuthenticationProvider.Instance;
我看到我正在制作一个AuthentcationProvider,但后来我不明白发生了什么,为什么会有比较,问题是什么?
感谢。
答案 0 :(得分:2)
这里的?
和:
称为conditional operator(有时也称为三元运算符)。
您发布的代码与此相同:
AuthenticationProvider auth;
if ((level & Levels.Authentication) == Levels.Authentication) {
auth = GetAuthenticationProviderByName(authentication, authPhrase);
} else {
auth = DefaultAuthenticationProvider.Instance;
}
&
是“按位和”。这里用它来测试是否设置了Levels.Authentication
位。
答案 1 :(得分:1)
答案 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