具有多种类型的一个参数C#通用方法 [英] C# generic method with one parameter of multiple types

查看:924
本文介绍了具有多种类型的一个参数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< INT> ,并让 T 是隐式转换为主要,修复您的错误(或者我希望如此)。

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

这篇关于具有多种类型的一个参数C#通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆