一个方法如何只包含一个NotImplementedException并且仍然可以在不抛出的情况下运行?

Abe*_*bel 2 c# reflection notimplementedexception

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

C#,.NET 4.0:

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

而作为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 
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我运行以下代码,它只是工作.

// 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);

}
Run Code Online (Sandbox Code Playgroud)

不会抛出任何错误.同样如此GetValueDirect.我根据资源的名称猜测,只有在代码必须是CLSCompliant时才会抛出,但方法的主体在哪里?或者,换句话说,我该如何反映方法的实际主体?

Jon*_*eet 5

这是一种虚拟方法.据推测,Type.GetField()正在使用真实的实现返回派生类型 - 尝试打印info.GetType().(我刚试过我的盒子,System.RtFieldInfo例如它.)