【问题标题】:System.DirectoryServices.AccountManagement.PrincipalCollection - how to check if principal is a user or a group?System.DirectoryServices.AccountManagement.PrincipalCollection - 如何检查主体是用户还是组?
【发布时间】:2011-11-10 19:43:11
【问题描述】:

考虑以下代码:

GroupPrincipal gp = ... // gets a reference to a group

foreach (var principal in gp.Members)
 {
       // How can I determine if principle is a user or a group?         
 }

基本上我想知道的是(基于成员集合)哪些成员是用户,哪些是组。根据它们的类型,我需要触发额外的逻辑。

【问题讨论】:

    标签: c# .net active-directory


    【解决方案1】:

    简单:

    foreach (var principal in gp.Members)
    {
           // How can I determine if principle is a user or a group?         
        UserPrincipal user = (principal as UserPrincipal);
    
        if(user != null)   // it's a user!
        {
         ......
        }
        else
        {
            GroupPrincipal group = (principal as GroupPrincipal);
    
            if(group != null)  // it's a group 
            {
               ....
            }
        }
    }
    

    基本上,您只需使用 as 关键字转换为您感兴趣的类型 - 如果值为 null 则转换失败 - 否则成功。

    当然,另一种选择是获取类型并检查它:

    foreach (var principal in gp.Members)
    {
        Type type = principal.GetType();
    
        if(type == typeof(UserPrincipal))
        {
          ...
        }
        else if(type == typeof(GroupPrincipal))
        {
         .....
        }
    }
    

    【讨论】:

    • 或使用 'is' 运算符(例如 var result = principal is UserPrincipal),这可能在内部执行类似于这些选项之一的操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多