具有多种类型的一个参数C#通用方法

问题描述:

我在写一个通用的方法来检索AD组或用户,可以参数的问题,有两种类型中的一种 - 无论是 System.DirectoryServices.AccountManagement GroupPrincipal UserPrincipal

I'm having a problem writing a generic method to retrieve AD Groups or Users with a parameter that can be one of two types - either System.DirectoryServices.AccountManagement GroupPrincipal or UserPrincipal

的方法如下: -

private static IEnumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
{
   PrincipalSearcher ps = new PrincipalSearcher();
   ps.QueryFilter = GroupOrUserPrincipal;

   etc.........
}

问题是GroupOrUserPrincipal是显示以下错误: -

The problem is the GroupOrUserPrincipal is showing the following error:-

无法隐式转换类型'T'到
系统。 DirectoryServices.AccountManagement.Principal

Cannot implicitly convert type 'T' to System.DirectoryServices.AccountManagement.Principal

我是否能做到这一点还是我失去了一些东西?

Am I able to do this or am I missing something ?

您应该限制 T 来的类型,你的方法是有道理的:

You should restrict T to types that your method makes sense for:

private static IENumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
        where T : Principal
{
      // .....

这是防止通话 GetGroupsOrUsers&LT; INT&GT; ,并让 T 是隐式转换为主要,修复您的错误(或者我希望如此)。

That prevents calls of GetGroupsOrUsers<int>, and lets T be implicitly converted to Principal, fixing your error (or so I hope).