【问题标题】:"Operation could destablize the runtime" and DynamicMethod with value types“操作可能会破坏运行时的稳定性”和具有值类型的动态方法
【发布时间】:2009-08-14 13:13:44
【问题描述】:

我正在尝试概括以下 IL(来自 Reflector):

.method private hidebysig instance void SetValue(valuetype Test.TestFixture/ValueSource& thing, string 'value') cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: ldarg.2 
    L_0003: call instance void Test.TestFixture/ValueSource::set_Value(string)
    L_0008: nop 
    L_0009: ret 
}

但是,当我尝试使用 DynamicMethod 重现此 IL 时:

        [Test]
    public void Test_with_DynamicMethod()
    {
        var sourceType = typeof(ValueSource);
        PropertyInfo property = sourceType.GetProperty("Value");

        var setter = property.GetSetMethod(true);
        var method = new DynamicMethod("Set" + property.Name, null, new[] { sourceType.MakeByRefType(), typeof(string) }, true);
        var gen = method.GetILGenerator();

        gen.Emit(OpCodes.Ldarg_1); // Load input to stack
        gen.Emit(OpCodes.Ldarg_2); // Load value to stack
        gen.Emit(OpCodes.Call, setter); // Call the setter method
        gen.Emit(OpCodes.Ret);

        var result = (SetValueDelegate)method.CreateDelegate(typeof(SetValueDelegate));

        var source = new ValueSource();

        result(ref source, "hello");

        source.Value.ShouldEqual("hello");
    }

    public delegate void SetValueDelegate(ref ValueSource source, string value);

我收到“操作可能会破坏运行时”的异常。 IL似乎与我相同,有什么想法吗? ValueSource 是一个值类型,这也是我在这里做一个 ref 参数的原因。

编辑

这是 ValueSource 类型:

public struct ValueSource
{
   public string Value { get; set; }
}

【问题讨论】:

  • 有任何机会(希望是简单的)ValueSource,以便我们可以重现...?
  • 另外 - 值类型应该真的是不可变的,这会使这个没有意义......

标签: c# cil


【解决方案1】:

将 args 更改为 0/1(不是 1/2):

    gen.Emit(OpCodes.Ldarg_0); // Load input to stack
    gen.Emit(OpCodes.Ldarg_1); // Load value to stack

因为动态方法似乎是作为静态创建的,而不是实例(您的原始方法是实例) - 因此 args 减一。

(抱歉原来的错误答案 - 您可以将其他代码保留为true

【讨论】:

  • 是的,就是这样。下次我将模板方法设为静态。
猜你喜欢
  • 2010-09-27
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多