如何在Type.GetType()中指定泛型?

时间:2017-11-15 13:31:40

标签: c# generics reflection

我正在开发一个VS扩展,它将为文件生成文档注释。 Roslyn提供了允许处理源代码和添加注释的类。我遇到的具体问题是确定类声明中基类或接口的完全限定名称。例如:

using System;
using System.Collections;
using System.Linq;

public class MyClass: IEnumerable
{ ... }

我想要生成:

<summary></summary>
<seealso cref="System.Collections.IEnumerable"/>

我通过循环遍历每个using指令来确定IEnumerable是在System.Collections中定义的,以获取IdentifierName或QualifiedName并附加接口名称以生成潜在的完全限定名称。然后我调用Type.GetType(potentialFullyQualifiedName),如果名称有效则返回类型,否则返回null。如果返回的值不为null,那么我知道我有一个有效的完全限定名。对于上面的例子,我先试试 “System.IEnumerable”返回null。然后“System.Collections.IEnumerable”返回一个类型,所以我知道我有正确的完全限定名。到目前为止一切都很好。

但是,如果我将正在处理的代码更改为:

using System;
using System.Collections.Generic;
using System.Linq;

public class MyClass : IEnumerable<int>
{ ... }

我尝试的一切都返回null。 IEnumerable在System.Collections.Generic中,所以我将进一步讨论限制。

没有:

System.Collections.Generic.IEnumerable
System.Collections.Generic.IEnumerable<>
System.Collections.Generic.IEnumerable<T>
System.Collections.Generic.IEnumerable<int>
System.Collections.Generic.IEnumerable<out T>
System.Collections.Generic.IEnumberable`1

从Type.GetType()返回一个类型。如何指定接口名称以使Type.GetType()返回类型而不是null?

在查看下面的第一条评论和第一条答案后,两者都没有提供“解决方案”,看来我需要添加更多信息。

我上面包含的源代码就是源代码,或者换句话说,文本,它被解析为创建一个语法模型,然后我会经历。我无法实例化Class1对象,因为源代码尚未编译,并且不是处理语法模型的程序集的一部分。我可以编译源代码来生成源代码的语义模型,但这可能是一个昂贵的操作,我宁愿避免。所以它归结为我如何确定IEnumerable实际上是System.Collections.Generic.IEnumerable,因为我只有IEnumerable作为文本?

1 个答案:

答案 0 :(得分:1)

这是因为泛型类的全名格式有点不同。它还包括通用类型的名称空间完整程序集标识字符串,并附在[]中。

我写了一个简短的例子来说明它。考虑我们有以下两种类型:

class NonGeneric : IEnumerable

class Generic : IEnumerable<string>

...以及以下代码将接口名称输出到控制台:

var nonGeneric = new NonGeneric();
var generic = new Generic();
string nonGenericName = nonGeneric.GetType().GetInterfaces().First().FullName;
string genericName = generic.GetType().GetInterfaces().First().FullName;

Console.WriteLine($"Non generic: {nonGenericName}");
Console.WriteLine($"Generic: {genericName}");

输出:

Non generic: System.Collections.IEnumerable
Generic: System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]

我希望它可以帮到你!

相关问题