如何通过名称获得 C # .Net Assembly?

有没有这样的东西:

AppDomain.CurrentDomain.GetAssemblyByName("TheAssemblyName")

因此,我们可以直接得到特定的程序集,而不是通过 AppDomain.CurrentDomain.GetAssemblies()循环。

110397 次浏览

Have you tried looking at Assembly.Load(...)?

Have a look at the System.Reflection.Assembly class, in particular the Load method: MSDN

It depends on what you're trying to accomplish.

If you just want to get the assembly, then you should call System.Reflection.Assembly.Load() (as already pointed out). That's because .NET automatically checks if the assembly has already been loaded into the current AppDomain and doesn't load it again if it has been.

If you're just trying to check whether the assembly has been loaded or not (for some diagnostics reason, perhaps) then you do have to loop over all the loaded assemblies.

Another reason you might want to loop is if you know only some of the assembly information (eg. you're not sure of the version). That is, you know enough to "recognise it when you see it", but not enough to load it. That is a fairly obscure and unlikely scenario, though.

For those who just need to access the assembly's metadata (version, etc.) check out Assembly.ReflectionOnlyLoad(name), which is able to load only the metadata, possibly saving on memory and IO.

I resolved with LINQ

Assembly GetAssemblyByName(string name)
{
return AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(assembly => assembly.GetName().Name == name);
}

You can write an extension method that does what you need.

This method will only enumerate loaded assemblies, if you possibly need to load it, use Assembly.Load from the accepted answer.

public static class AppDomainExtensions
{
public static Assembly GetAssemblyByName(this AppDomain domain, string assemblyName)
{
return domain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == assemblyName);
}
}

Then you call this method on an AppDomain like this:

Assembly a = AppDomain.CurrentDomain.GetAssemblyByName("SomeAssembly")

If SomeAssembly is loaded into the current AppDomain the method will return it, otherwise it will return null.

If this is an assembly you have referenced, I like to write a class like the following:

namespace MyLibrary {
public static class MyLibraryAssembly {
public static readonly Assembly Value = typeof(MyLibraryAssembly).Assembly;
}
}

and then whenever you need a reference to that assembly:

var assembly = MyLibraryAssembly.Value;