考虑以下代码:
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/