一个方法怎么可能只包含NotImplementedException,并且仍然在不引发的情况下运行

本文关键字:运行 情况下 一个 方法 怎么可能 NotImplementedException 包含 | 更新日期: 2023-09-27 18:29:19

如果我在Reflector中检查FieldInfo.SetValueDirect,它看起来如下:

C#,.NET 4.0:

[CLSCompliant(false)]
public virtual void SetValueDirect(TypedReference obj, object value)
{
    throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}

作为IL:

.method public hidebysig newslot virtual instance void SetValueDirect(valuetype System.TypedReference obj, object 'value') cil managed
{
    .custom instance void System.CLSCompliantAttribute::.ctor(bool) = { bool(false) }
    .maxstack 8
    L_0000: ldstr "NotSupported_AbstractNonCLS"
    L_0005: call string System.Environment::GetResourceString(string)
    L_000a: newobj instance void System.NotSupportedException::.ctor(string)
    L_000f: throw 
}

但是,如果我运行以下代码,它就可以运行

// test struct:
public struct TestFields
{
    public int MaxValue;
    public Guid SomeGuid;   // req for MakeTypeRef, which doesn't like primitives
}

[Test]
public void SettingFieldThroughSetValueDirect()
{
    TestFields testValue = new TestFields { MaxValue = 1234 };
    FieldInfo info = testValue.GetType().GetField("MaxValue");
    Assert.IsNotNull(info);
    // TestFields.SomeGuid exists as a field
    TypedReference reference = TypedReference.MakeTypedReference(
        testValue, 
        new [] { fields.GetType().GetField("SomeGuid") });
    int value = (int)info.GetValueDirect(reference, );
    info.SetValueDirect(reference, 4096);
    // assert that this actually worked
    Assert.AreEqual(4096, fields.MaxValue);
}

没有引发错误。GetValueDirect也是如此。根据资源的名称,我的猜测是,只有当代码必须符合CLSCompliant时才会抛出,但方法的主体在哪里?或者,换言之,我如何才能反映方法的实际主体?

一个方法怎么可能只包含NotImplementedException,并且仍然在不引发的情况下运行

这是一个虚拟方法。假设Type.GetField()正在返回一个带有实际实现的派生的类型——请尝试打印info.GetType()。(我刚刚试过我的盒子,它显示了System.RtFieldInfo。)

Debugger显示testValue.GetType().GetField("MaxValue")返回的RtFieldInfo是从RuntimeFieldInfo派生而来的,RuntimeFieldInfo是从FieldInfo派生的。所以这个方法很可能在其中一个类中被覆盖了。很可能是因为运行时类型和仅反射加载的程序集的类型有不同的FieldInfo实现

相关文章: