说我有这么一点代码:
public static void LoadSomething(Type t)
{
var t1 = Type.GetType(t.AssemblyQualifiedName);
var t2 = t
.Assembly
.GetTypes()
.First(ta => ta.AssemblyQualifiedName == t.AssemblyQualifiedName);
}
Run Code Online (Sandbox Code Playgroud)
会发生什么是t1为空且t2 不为空.我很困惑,因为如果我这么称呼它......
LoadSomething(typeof(SomeObject));
Run Code Online (Sandbox Code Playgroud)
然后它们都不是null但我实际上做的更像是这样(不是真的,这是大规模简化但它说明了我的观点):
LoadSomething(Assembly.LoadFile(@"C:\....dll").GetTypes().First());
Run Code Online (Sandbox Code Playgroud)
所以问题的第一部分(供我参考)是......
在第二种情况下,由于必须加载程序集并且我找到了它的类型,为什么Type.GetType返回null?
其次(实际解决我的问题)......
当我只将汇编限定名称作为字符串(我之前已经使用Assembly.Load方法加载)时,是否还有其他方法可以加载类型?
ken*_*n2k 21
当我只将汇编限定名称作为字符串(我之前已经使用Assembly.Load方法加载)时,是否还有其他方法可以加载类型?
是.有一个GetType过载允许.它需要一个"程序集解析器"函数作为参数:
public static Type LoadSomething(string assemblyQualifiedName)
{
// This will return null
// Just here to test that the simple GetType overload can't return the actual type
var t0 = Type.GetType(assemblyQualifiedName);
// Throws exception is type was not found
return Type.GetType(
assemblyQualifiedName,
(name) =>
{
// Returns the assembly of the type by enumerating loaded assemblies
// in the app domain
return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).FirstOrDefault();
},
null,
true);
}
private static void Main(string[] args)
{
// Dynamically loads an assembly
var assembly = Assembly.LoadFrom(@"C:\...\ClassLibrary1.dll");
// Load the types using its assembly qualified name
var loadedType = LoadSomething("ClassLibrary1.Class1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7790 次 |
| 最近记录: |