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

标签 c# .net

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

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/

相关文章:

c# - .NET Xml 反序列化,xsi :type attribute 的问题/错误

.net - 建议在 asp.net mvc3 中使用富文本编辑器,其中包含页面大小设置、打印预览和页面缩放选项

c# - 了解 MongoDB Aggregate 和 GroupBy

c# - .Net 中的多个音频输出

c# - SqlCommand SQL 语句被执行两次

.net - EPPlus 无效地址格式错误

c# - 动态 Windows 窗体控件创建 - 一般问题

c# - 加载配置文件时出错 : Access to path c:\Program Files (x86)\. .. 被拒绝

.net - .NET应用程序是否不受经典指针错误的影响?

c# - IDictionary<,> 逆变?