gpt4 book ai didi

c# - 是否可以将 Type.GetType 与动态加载的程序集一起使用?

转载 作者:可可西里 更新时间:2023-11-01 03:08:42 25 4
gpt4 key购买 nike

假设我有这么一小段代码:

public static void LoadSomething(Type t)
{
var t1 = Type.GetType(t.AssemblyQualifiedName);

var t2 = t
.Assembly
.GetTypes()
.First(ta => ta.AssemblyQualifiedName == t.AssemblyQualifiedName);
}

发生的情况是 t1 为 null 而 t2 为 not null。我很困惑,因为如果我这样调用它......

LoadSomething(typeof(SomeObject));

然后两者都为空,但我实际做的更像是这样(不是真的,这被大大简化了,但它说明了我的观点):

LoadSomething(Assembly.LoadFile(@"C:\....dll").GetTypes().First());

所以我的问题的第一部分(供我引用)是...

在第二种情况下,由于必须加载程序集并且我从中找到了类型,为什么 Type.GetType 返回 null?

其次(实际解决我的问题)...

当我仅将程序集限定名称作为字符串(我知道之前已使用 Assembly.Load 方法加载)时,是否有其他方法可以加载类型?

最佳答案

Is there some other way that I could load a type when I only have the assembly qualified name as a string (that I know has been previously loaded by using the Assembly.Load methods)?

是的。有一个GetType overload这允许。它采用“程序集解析器”函数作为参数:

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();
}

关于c# - 是否可以将 Type.GetType 与动态加载的程序集一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11430654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com