代码之家  ›  专栏  ›  技术社区  ›  rrrr-o

为什么GetName在系统中。反射反编译时,程序集是否会抛出NotImplementedException?

  •  0
  • rrrr-o  · 技术社区  · 8 年前

    在调试一个问题时,我深入到了mscorlib,特别是 GetName() 在里面 System.Reflection.Assembly .

    查看dotPeek中方法的代码,以及 reference source 的代码 GetName() 似乎什么都没有 NotImplementedException :

    #if FEATURE_CORECLR
        [System.Security.SecurityCritical] // auto-generated
    #endif
        public virtual AssemblyName GetName()
        {
            return GetName(false);
        }
    
    #if FEATURE_CORECLR
        [System.Security.SecurityCritical] // auto-generated
    #endif
        public virtual AssemblyName GetName(bool copiedName)
        {
            throw new NotImplementedException();
        }
    

    有人能解释为什么这看起来会引发异常,但使用一行代码,例如 typeof(object).GetTypeInfo().Assembly.GetName().Version.ToString() 返回DLL的正确版本?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Lasse V. Karlsen    8 年前

    那是因为 Assembly 是基类,则在运行时(在此特定设置中)返回的实际对象是 RuntimeAssembly 哪一个 做 实施该方法。

    取决于您如何获得 装配 对象,有不同的实际类型在起作用,无论是用于实际运行时代码还是仅用于反射探索或诸如此类。

    但是 装配 是基类。

    我可以毫不含糊地说,因为 装配 类是抽象的,从 reference source :

    public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable
    

    而且 documented :

    [System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
    [System.Runtime.InteropServices.ComVisible(true)]
    public abstract class Assembly : System.Reflection.ICustomAttributeProvider, System.Runtime.InteropServices._Assembly, System.Runtime.Serialization.ISerializable, System.Security.IEvidenceFactory
    

    因此,任何符合 装配 变量必须是派生类。