繁体   English   中英

System.DirectoryServices.AccountManagement.PrincipalCollection - 如何检查主体是用户还是组?

[英]System.DirectoryServices.AccountManagement.PrincipalCollection - how to check if principal is a user or a group?

请考虑以下代码:

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?         
 }

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

简单:

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))
    {
     .....
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM