在安全和非安全之间切换 DirectoryServices.AccountManagement.PrincipalContext

Switch between secure and non-secure DirectoryServices.AccountManagement.PrincipalContext

我正在努力解决以下问题,这就是我现在所拥有的并且它正在工作但是。

 public PrincipalContext getPrincipalContext(bool secured)
 {
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
        secured ?  DomainName + ":636" : DomainName,
        Container,
        secured ? ContextOptions.SecureSocketLayer | ContextOptions.Negotiate : ContextOptions.SimpleBind,
        userName,
        password);
    return oPrincipalContext;
 }

想做这样的事情

secured ?  PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
            DomainName + ":636",
            Container,
            ContextOptions.SecureSocketLayer | ContextOptions.Negotiate 
            userName,
            password); 
        :
          PrincipalContext oPrincipalContext = new  PrincipalContext(ContextType.Domain,
            DomainName,
            Container,
            ContextOptions.SimpleBind);
    return oPrincipalContext;

我认为这是可能的,但无法编译。有人可以帮我找到正确的方法吗?

可能是这样的:

 PrincipalContext oPrincipalContext = secured ? 
         new PrincipalContext(ContextType.Domain,
            DomainName + ":636",
            Container,
            ContextOptions.SecureSocketLayer | ContextOptions.Negotiate 
            userName,
            password); 
        :
          new PrincipalContext(ContextType.Domain,
            DomainName,
            Container,
            ContextOptions.SimpleBind );

或者你为什么不直接使用 if, else