我目前正在编写一个方法,它可以完成以下几件事:
- 验证操作系统版本。
- 验证操作系统平台。
- 验证帐户不为空。
- 验证帐户是否具有正确的角色。
现在,如果我实现传统的嵌套if,它就可以工作了。绝对零问题 - 然而,为了我认为的更干净的实现,已经变成了一个可爱的错误。
语法:
bool result = false;
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal role = new WindowsPrincipal(user);
result = ((Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion .Version.Major > 6
&& role != null && role.IsInRole(WindowsBuiltInRole.Administrator)
? true : false);
但我收到以下异常。
Operator
&&
cannot be applied to the operands of typeSystem.PlatformID
andbool
.
我真的不知道为什么它不起作用,它应该起作用。我是否错误地实现了逻辑或者什么,我真的很茫然。
这个语法确实有效,但是当我将其转换为上面的条件时,它就不起作用了。
if(Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion
.Version.Major > 6)
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal role = new WindowsPrincipal(user);
if(role != null)
{
if(role.IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
}
return false;
}
return false;
更新:
这是出现红色波浪线的地方,Visual Studio 给出了上述错误:
PlatformID.Win32NT && Environment.OSVersion.Version.Major > 6
最佳答案
你的条件可以重写如下:
bool result = Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version.Major > 6 &&
role.IsInRole(WindowsBuiltInRole.Administrator);
请注意,您可以跳过“角色”空检查,因为在您的情况下它永远不会为空。
编辑
就您的更新而言,问题出在这部分:
bool result = PlatformID.Win32NT; // <-- this part can't compile, it's not a boolean
我相信你想写的是:
bool result = Environment.OSVersion.Platform == PlatformID.Win32NT; // along with your other conditions
编辑2
既然您已经问过为什么您的示例不起作用(不确定您有什么拼写错误或到底发生了什么),但此代码也可以编译(注意: I不会这样写,只是说):
bool result = ((Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version.Major > 6
&& role != null && role.IsInRole(WindowsBuiltInRole.Administrator)
? true
: false));
关于c# - 条件运算符,验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17768891/