C# - 了解泛型类型的基本类型

时间:2014-12-11 07:31:18

标签: c# func

如何找出泛型类型的基本类型?

例如

 Func<A, B>

我希望能够说这是一个Func&lt;&gt; ..但显然,Func&lt;,&gt;不同于Func&lt;&gt; - 有没有办法以某种方式捕捉他们两个,或Func&lt; ,,,&gt;等?

3 个答案:

答案 0 :(得分:3)

您正在寻找GetGenericTypeDefinition

var t = typeof(Func<int, string>);
var tGeneric = t.GetGenericTypeDefinition();
Assert.AreEqual(typeof(Func<,>), tGeneric);

如果您想知道某个类型是否是众多Func<>变体之一,那么您最好的只是做这样的事情。检查类型名称,如其他地方所建议的那样绝对不是检查类型标识的方法:

static Type[] funcGenerics = new[]{
  typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>),
  /* and so on... */
}
//there are other ways to do the above - but this is the most explicit.


static bool IsFuncType(Type t)
{
  if(t.IsGenericTypeDefinition)
    return funcGenerics.Any(tt => tt == t);
  else if(t.IsGenericType) 
    return IsFuncType(t.GetGenericTypeDefinition());
  return false;
}

您的术语不正确 - 我怀疑您为什么要对您的问题进行投票。基类型是类型继承的基类型(不是接口,它是不同的,虽然在概念上非常相似)。

通用类型定义最好被认为是 喜欢 一个模板(因为术语&#39;模板&#39;用于C ++)而且,虽然视觉上相似,但它们在实施方面却大相径庭。)

更准确地说,Func<,>是通用类型定义,而Func<int, string>已关闭通用(&#39;泛型类型&#39;)。

你也可以有一个开放的泛型,这是类型参数是通用参数的地方 - 例如,给定:

class MyType<T> : List<T> { }

然后List<T>是一个带有泛型类型定义List<>的开放式泛型,因为T是一个通用参数,在具体参数引用MyType<T>之前不会关闭类型参数,例如intstring

最后,仅仅因为一堆泛型类型共享相同的公用名,例如Func<>Func<,>Func<,,>并不意味着它们有任何关联。在类型级别,没有明确的连接,这就是为什么你必须检查所有这些类型的身份,以及为什么没有共同的基础&#39;就像你说的那样。但是,如果它们都有一个公共接口或基类,那么你可以 - 通过检查与该接口或基类型的兼容性。

给定泛型类型定义,您可以使用MakeGenericType构造泛型类型,正如Jeffrey Zhang所提到的那样。

答案 1 :(得分:1)

不,你不能,没有Gerneric Type的基本类型。如果要按类型参数获取特定的泛型类型,可以使用MakeGenericType。例如:

//get Func<int, string> type
typeof(Func<>).MakeGenericType(typeof(int), typeof(string));

如果要从指定的泛型类型获取通用类型,可以使用GetGenericTypeDefinition。例如:

//get Func<,> type
typeof(Func<int, string>).GetGenericTypeDefinition();

答案 2 :(得分:0)

因为Func< A, B >不会从Func<>继承,所以它是基于Func<,>的通用。

但是,你会注意到

typeof(Func<int, int>).FullName // equals "System.Func`2...
typeof(Func<int, int, int>).FullName // equals "System.Func`3...

这有点难看,但你可以使用像

这样的东西
YourType.FullName.StartsWith("System.Func")

希望有所帮助

编辑: 为什么不使用YourType.GetGenericTypeDefinition()

因为typeof(Func<int, int>).GetGenericTypeDefinition()返回Func<,>

typeof(Func<int, int, int>).GetGenericTypeDefinition()返回Func<,,>

Func<,>Func<,,>的类型不同。

相关问题