2

我目前正在编写一个可以做几件事的方法

  • 验证操作系统版本
  • 验证操作系统平台
  • 验证 Account 不是 null
  • 验证帐户的角色是否正确

现在,如果我实现传统的嵌套,它是否有效。绝对零问题 - 但是,为了我认为更清洁的实现,它变成了一个可爱的错误。

语法:

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);

但我收到以下异常

运算符&&不能应用于 和 类型的操作 System.PlatformIDbool

我真的不确定为什么它不起作用,它应该。我是在错误地实现逻辑还是什么,我真的很茫然。

这种语法确实有效,但是当我将其转换为上述条件时,它就不起作用了。

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
4

3 回答 3

2

您实际上不需要使用条件运算符——事实上… ? true : false根本没有任何效果。

尝试像这样重写您的代码:

bool result = 
    (Environment.OSVersion.Platform == PlatformID.Win32NT) && 
    (Environment.OSVersion.Version.Major > 6) &&
    (role != null) && 
    (role.IsInRole(WindowsBuiltInRole.Administrator));
于 2013-07-21T04:04:46.820 回答
2

您的条件可以这样重写:

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

既然您问过为什么您的示例不起作用(不确定您有什么错字或到底发生了什么),但这段代码也可以编译(注意: 我不会那样写,只是说):

bool result = ((Environment.OSVersion.Platform == PlatformID.Win32NT &&
                Environment.OSVersion.Version.Major > 6
                && role != null && role.IsInRole(WindowsBuiltInRole.Administrator)
                    ? true
                    : false));
于 2013-07-21T04:10:29.597 回答
0

没测试过,可以试试

   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))));

    return result;
于 2013-07-21T04:26:33.063 回答