我在编写通用方法来检索 AD 组或用户时遇到问题,该方法的参数可以是两种类型之一 - System.DirectoryServices.AccountManagement GroupPrincipal
或 UserPrincipal
方法如下:-
private static IEnumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
{
PrincipalSearcher ps = new PrincipalSearcher();
ps.QueryFilter = GroupOrUserPrincipal;
etc.........
}
问题是 GroupOrUserPrincipal 显示以下错误:-
Cannot implicitly convert type 'T' to System.DirectoryServices.AccountManagement.Principal
我能做到这一点还是我错过了什么?
最佳答案
你应该限制T
对您的方法有意义的类型:
private static IENumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
where T : Principal
{
// .....
这会阻止调用 GetGroupsOrUsers<int>
,并让 T
隐式转换为 Principal
,修复你的错误(或者我希望如此)。
关于具有多种类型的一个参数的C#泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8062782/