Reflection.Emit创建属性

时间:2015-01-30 16:30:46

标签: c# reflection.emit

如何使用反射创建Property1?

public IProp Property1
{
    get
    {
        return new TestClass(TestMethod);
    }
}

private void TestMethod()
{
...
}

我正在尝试

    var propertyBuilder = typeBuilder.DefineProperty("Property1", 
        PropertyAttributes.None, typeof(IProp), Type.EmptyTypes);
    propertyBuilder.SetGetMethod(GenerateGetter(typeBuilder, testMethodInfo));

    MethodBuilder GenerateGetter(TypeBuilder typeBuilder, MethodInfo TestMethod)
    {
        var getterBuilder = typeBuilder.DefineMethod(TestMethod.Name,
            METHOD_ATTRIBUTES, TestMethod.ReturnType, Type.EmptyTypes);

        var actionCtor = typeof(Action).GetConstructors().Single();
        var testClassCtor = typeof(TestClass).GetConstructor(new[] { typeof(Action) });

        var il = getterBuilder.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldftn, TestMethod);
        il.Emit(OpCodes.Newobj, actionCtor);
        il.Emit(OpCodes.Newobj, testClassCtor);
        il.Emit(OpCodes.Ret);
        return getterBuilder;
    }

但是我有System.Reflection.TargetException(Object与目标类型不匹配)。我想我有错误,因为我的IL代码很糟糕。

1 个答案:

答案 0 :(得分:0)

我替换了

var getterBuilder = typeBuilder.DefineMethod(TestMethod.Name,
        METHOD_ATTRIBUTES, TestMethod.ReturnType, Type.EmptyTypes);

var getterBuilder = typeBuilder.DefineMethod(TestMethod.Name,
        METHOD_ATTRIBUTES, typeof(IProp), Type.EmptyTypes);