![](/img/trans.png)
[英]Does a System.DirectoryServices.AccountManagement.Principal ever have a null GUID?
[英]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.