为什么System.Reflection.Assembly中的GetName似乎在反编译时抛出NotImplementedException?

问题描述 投票:0回答:1

在调试问题时,我正在挖掘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的正确版本?

c# reflection mscorlib
1个回答
3
投票

那是因为Assembly是一个基类,你在运行时得到的实际对象(在这个特定的设置中)是一个实现该方法的RuntimeAssembly

根据您获取Assembly对象的方式,有不同的实际类型,无论是实际运行时代码还是仅反射探测器等等。

但是Assembly是一个基类。

我可以毫不含糊地说这是因为Assembly类是抽象的,从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

因此,适合Assembly变量的对象的任何实例都必须是派生类。

© www.soinside.com 2019 - 2024. All rights reserved.