当我列出当前 AppDomain 中的所有类型时,我会看到带有通用占位符的通用类型。但是,如果我使用类型实例化泛型类型,然后列出 appDomain 中的所有类型,则我看不到新创建的封闭类型。
在下面的示例中,输出仅为:
Foo`1[T]
我正在寻找封闭类型:
Foo`1[System.Int32]
有没有办法查看运行时根据我的开放泛型类型为我创建的封闭类型?
class Foo<T>
{
}
class Program
{
static void Main(string[] args)
{
var tmp = new Foo<int>();
ListTypes();
}
private static void ListTypes()
{
var types = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name.Contains("Foo")
select type;
foreach (var type in types)
Console.WriteLine(type.ToString());
}
}
我还尝试通过泛型参数查找所有类型,希望能发现封闭类型。
class Foo<T>
{
}
class Bar
{
}
class Program
{
static void Main(string[] args)
{
var tmp = new Foo<Bar>();
ListTypes();
}
private static void ListTypes()
{
var types = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsGenericType
&& type.GetGenericArguments().Contains(typeof(Bar))
select type;
foreach (var type in types)
Console.WriteLine(type.ToString());
}
}
这只是为了满足我的好奇心。
据我所知,在这种情况下Foo<T>
是一个开放的未绑定泛型类型,因此在运行时 CLR 将使用它作为蓝图/骨架来构造和关闭具有指定类型参数类型的泛型类型(Foo<int>
, Foo<object>
, ETC。)。所以基本上Foo<int>
是一个运行时构造的实现Foo<T>
骨骼。
现在,在运行时您可以获得以下类型Foo<int>
要么通过使用typeof(Foo<int>)
or typeof(Foo<>).MakeGenericType(new[] { typeof(int) })
这不一样Type
这样做是没有意义的。但仔细观察你会发现两者typeof(Foo<T>)
and typeof(Foo<int>)
共享相同的元数据令牌和 GUID。
另一个有趣的事情是typeof(Foo<int>).Assembly
将是您所期望的,但正如您已经注意到的那样,您无法从程序集中获得该类型。
那是因为Foo<int>
未在程序集中定义(您可以使用 Reflector/ILSpy 检查程序集元数据)。在运行时,CLR 将创建(“构造”)一个专门的(“封闭的”)版本Foo<T>
for Foo<int>
(因此 - 构造无界开放泛型类型定义的封闭类型)并“给”它一个Type
。因此,除非 CLR 以某种方式直接公开它在运行时生成的封闭泛型类型列表,否则您就不走运了。
这里还有一个片段可以证实我所说的:
即使每次构造一个泛型类型,例如 Node
http://msdn.microsoft.com/en-us/magazine/cc163683.aspx http://msdn.microsoft.com/en-us/magazine/cc163683.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)