Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

c# - Is it possible to use Type.GetType with a dynamically loaded assembly?

Say I have this little bit of code:

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

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

What happens is that t1 is null and t2 is not null. I was confused since if I call it like so...

LoadSomething(typeof(SomeObject));

then neither are null but what I am actually doing is more like this (not really, this is massively simplified but it illustrates my point):

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

So the first part of my question (for my information) is...

In the second case, since the assembly must be loaded up and I found the type out of it, why does Type.GetType return null?

And secondly (to actually solve my problem)...

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)?

Yes. There is a GetType overload that allows that. It takes an "assembly resolver" function as parameter:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...