How to tell if a .NET assembly is dynamic?

﹥>﹥吖頭↗ 提交于 2019-12-03 14:21:18

问题


When iterating through a set of assemblies, e.g. AppDomain.CurrentDomain.GetAssemblies(), dynamic assemblies will throw a NotSuportedException if you try to access properties like CodeBase. How can you tell that an assembly is dynamic without triggering and catching the NotSupportedException?


回答1:


To check if the assembly is dynamic:

if (assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)

This took me a while to figure out, so here it is asked and answered.

Update:

In .NET 4.0, there is now a property:

if (assembly.IsDynamic)



回答2:


In .NET 4 you can also check the Assembly.IsDynamic property.




回答3:


Prior to .NET Framework 4, the simplest solution seems to be to check if the Assembly is of type System.Reflection.Emit.AssemblyBuilder. This is the solution we use on our team.

If you take a look at the AssemblyBuilder's CodeBase property implementation, it simply throws an exception, regardless of anything else. AssemblyBuilder is also a sealed class, so it's impossible for a derived class to change this behavior. So, if you have an AssemblyBuilder object, you can be certain that you can never call CodeBase or GetManifestResourceStream or a bunch of other methods.

public override string CodeBase
{
    get
    {
        throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
    }
}

And in .NET Framework 4, checking the Assembly.IsDynamic property should be preferable because it's more legible and perhaps more future-proof, in case some new class comes along that overrides IsDynamic. Since AssemblyBuilder.IsDynamic always returns true, this is more evidence that an AssemblyBuilder object is always equivalent to a "dynamic dll".

Here's the .NET 4 AssemblyBuilder's IsDynamic:

public override bool IsDynamic
{ 
    get {
        return true; 
    } 
}


来源:https://stackoverflow.com/questions/1423733/how-to-tell-if-a-net-assembly-is-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!