【发布时间】:2019-01-03 08:46:17
【问题描述】:
我正在尝试使用反射发射创建一个类的扩展。
而且它有点工作。
var extendwith = new List<Type>();
extendwith.Add(typeof(object));
var t = Utils.DynamicInherit<BaseTest>("Extended",typeof(UtilsTest).GetMethod(nameof(Testing)), extendwith);
var instance = Activator.CreateInstance(t, new TestClass(), new { A=1 });
public class BaseTest
{
public readonly TestClass testClass;
public object IsNotNull;
public BaseTest(TestClass testClass)
{
this.testClass = testClass;
}
}
public static void Testing(BaseTest baseTest, List<object> objects)
{
foreach(var t in objects)
{
baseTest.IsNotNull = t;
}
}
这里发生的情况是从 DynamicInherit 方法返回的类型 (t) 现在将继承自 BaseTest 类并具有包含 2 个参数(TestClass、Object)的构造函数
静态方法Testing 将在“构造类型”的构造函数内部调用。 使用此 IL 代码调用它。
constructorBuilder.Emit(OpCodes.Ldarg_0); //The this a referance to the created base class
constructorBuilder.Emit(OpCodes.Ldloc_0); //Reference to a List<Objects> that is passed in thorugh the constructor
constructorBuilder.Emit(OpCodes.Call, constructor); //The function to be called.. in this case the "public static void Testing(BaseTest baseTest, List<object> objects)"
这“按预期”工作,但我想将其更改为使用 lamda 表达式而不是静态函数..
var t = Utils.DynamicInherit<BaseTest>("Extended",(baseO, objects) => {foreach(var t in objects)
{
baseTest.IsNotNull = t;
}} ,
extendwith);
我知道我必须换行
constructorBuilder.Emit(OpCodes.Call, constructor);
但我无法弄清楚如何...... 有什么建议吗???
【问题讨论】:
标签: c# lambda reflection expression-trees