How to tell if a .NET assembly is dynamic?

为君一笑 提交于 2019-12-03 04:11:29
Mike Stockdale

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)

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

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