我正在尝试纠正一个Func,我可以使用它访问属性的get方法,但遇到了一个障碍。
下面的动态方法创建得很好,但是当调用它时,我会得到以下错误。
VerificationException,操作可能会破坏运行时的稳定。
我已经检查了il代码通过将其写入类而不是动态方法来发出有效的函数,所有这些看起来都很好。
我想这与打字问题有关,但我不知道在哪里,所以任何帮助都很感激。
示例类
public class DemoClass
{
public string Property{get;set;}
}
动态方法创建
var getMethods = new DynamicMethod(string.Empty,
typeof(string),
new Type[] {typeof(object) });
var ilGet = getMethods.GetILGenerator();
var falseGetLabel = ilGet.DefineLabel();
ilGet.Emit(OpCodes.Ldarg_1);
ilGet.Emit(OpCodes.Isinst, typeof(DemoClass));
ilGet.Emit(OpCodes.Brfalse_S, falseGetLabel);
ilGet.Emit(OpCodes.Ldarg_1);
ilGet.Emit(OpCodes.Isinst, typeof(DemoClass));
ilGet.Emit(OpCodes.Call, typeof(DemoClass).GetProperty("Property").GetMethod);
ilGet.Emit(OpCodes.Ret);
ilGet.MarkLabel(falseGetLabel);
ilGet.Emit(OpCodes.Newobj,
typeof(InvalidOperationException).GetConstructor(Type.EmptyTypes));
ilGet.Emit(OpCodes.Throw);
var f = (Func<object,string>)getMethods.CreateDelegate(
typeof(Func<object,string>));
var x = new DemoClass{Property = "9"};
Console.WriteLine(f(x)); <--- fails here