c# - System.DirectoryServices.AccountManagement.PrincipalCollection - 如何检查委托(delegate)人是用户还是组?

标签 c# .net 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?         
 }

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

最佳答案

简单:

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

关于c# - System.DirectoryServices.AccountManagement.PrincipalCollection - 如何检查委托(delegate)人是用户还是组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085354/

相关文章:

c# - Android 应用程序调试几秒钟然后停止

c# - Entity Framework 不使用更新的连接字符串

c# - List<T> 并发删除和添加

asp.net - 使用应用程序池标识的 IIS 应用程序丢失主 token ?

active-directory - Microsoft Graph AD 用户或人员 API 来搜索所有用户?

powershell - PowerShell Active Directory 需要打开哪些端口/服务才能正常运行?

c# - 在构造函数中将整数字段/属性分配为零

c# - 有没有办法通过代码自动打开或关闭 BizTalk 接收位置?

C# GetHashCode() 高性能哈希算法

.net - CIL和MSIL(IL)有什么区别?