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

JL.*_*JL. 6 .net c# active-directory

请考虑以下代码:

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?         
 }
Run Code Online (Sandbox Code Playgroud)

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

mar*_*c_s 12

简单:

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 
        {
           ....
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

foreach (var principal in gp.Members)
{
    Type type = principal.GetType();

    if(type == typeof(UserPrincipal))
    {
      ...
    }
    else if(type == typeof(GroupPrincipal))
    {
     .....
    }
}
Run Code Online (Sandbox Code Playgroud)