简体   繁体   中英

How to get C#.Net Assembly by name?

Is there something like:

AppDomain.CurrentDomain.GetAssemblyByName("TheAssemblyName")

so instead of looping through AppDomain.CurrentDomain.GetAssemblies() , we could just get the specific assembly directly.

您是否尝试过查看Assembly.Load(...)

I resolved with LINQ

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

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.

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;

对于那些只需要访问程序集元数据(版本等)的人,请查看 Assembly.ReflectionOnlyLoad(name),它只能加载元数据,可能会节省内存和 IO。

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 .

看看 System.Reflection.Assembly 类,特别是 Load 方法: MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM