c# - 一个方法如何只包含一个 NotImplementedException 并且仍然运行而不抛出?

标签 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"));
}

作为 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 时才会抛出此消息。 ,但是方法的主体在哪里?或者,换句话说,我如何反射(reflect)方法的实际主体?

最佳答案

这是一个虚方法。据推测,Type.GetField() 正在返回具有实际实现的派生 类型 - 尝试打印 info.GetType()。 (我刚刚在我的盒子上试过,它显示了 System.RtFieldInfo 例如。)

关于c# - 一个方法如何只包含一个 NotImplementedException 并且仍然运行而不抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9927137/

相关文章:

Java - 当代理方法返回类型为 Future 时出现异常

c# - 如何在 C# 中获取所有 ISO 3166-1 国家/地区的数字代码

javascript - JavaScript 中的反射

c# - 如何将类转换为 Dictionary<string,string>?

c# - 转换使用反射创建的泛型类型实例

c# - 警告 CA1065 Microsoft 设计未实现异常

c# - 当子类不使用抽象类中的函数时,是否有使用 NotImplementedException 的替代方法?

scala - 如何设置 IntelliJ 将 Scala 的 "???"方法识别为 TODO

c# - Windows 键的 SendKey 是什么

c# - 将类型 `System.Collections.IEnumerator` 转换为 `System.Collections.Generic.IEnumerator`