【发布时间】:2012-07-27 05:36:39
【问题描述】:
解决问题
我遇到了我不理解的 Type.GetType(string typeName) 行为。
获取List<int>的类型时,指定类型为即可
System.Collections.Generic.List`1[[System.Int32]]
但是,对于HashSet<int>,我必须像这样指定一个完全限定的类型名称
System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
如果我遗漏了任何程序集、版本、文化或公钥标记,则不会解析类型。
重现代码
// Returns expected type:
Type tListWorks =
Type.GetType("System.Collections.Generic.List`1[[System.Int32]]");
// Returns null:
Type tHashSetNull =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]]");
// Returns expected type:
Type tHashSetWorks =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
// Returns null (omitted Culture):
Type tHashSetNoCultureFails =
Type.GetType("System.Collections.Generic.HashSet`1[[System.Int32]], System.Core, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089");
问题
- 为什么我必须完全符合
HashSet<T>而不是List<T>? - 鉴于必须指定版本限定,如果 .NET 运行时是 3.5(第一个具有
HashSet<T>)或更高版本(例如 .NET 4.5)怎么办?如果运行时完全像 Silverlight 或 Mono 怎么办?
【问题讨论】:
-
这应该也可以(虽然我没试过):
System.Collections.Generic.HashSet1[[System.Int32]], System.Core` -
@Andrey:这也是我的期望,但这行不通。
-
我很快在 F# Interactive(有效)以及 PowerShell 和 Roslyn(无效)中尝试了短版本。 F# Interactive 给了我
Binding session to 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll'...。因为它显然不解析字符串,所以我使用了一些反射器,并且正如预期的那样,它安装了自定义AppDomain.CurrentDomain.AssemblyResolve。因此,如果您使用允许更短名称的自定义程序集解析器,则应该可以指定更短的名称。
标签: .net