gpt4 book ai didi

c# - 如何创建具有反射类型的委托(delegate)闭包

转载 作者:太空狗 更新时间:2023-10-30 01:23:22 25 4
gpt4 key购买 nike

如何创建一个使用反射类型参数的闭包?以 .net 3.5 为目标

如果没有反射(reflection)我会

void Main()
{
int i = 0;
Action<Foo> doSomething = (foo) => i += foo.GetNumber();
var myFoo = new Foo();
myFoo.UseFoo(doSomething);
Console.WriteLine(i);
}

class Foo
{
public int GetNumber() { return 4; }
public void UseFoo(Action<Foo> doSomething)
{
doSomething(this);
}
}

Foo 是通过另一个程序集反射获得的类型时,我将如何设置 doSomething

void Main()
{
Type fooType = GetType("Foo");
int i = 0;
object doSomething = // ???;

var myFoo = Activator.CreateInstance(fooType);
fooType.GetMethod("UseFoo").Invoke(myFoo, new object[] { doSomething });
Console.WriteLine(i);
}

最佳答案

我使用了 DocXcz 和 Nikola Anusev 的答案来解决这个问题

static void Main()
{
var fooType = typeof(Foo); // get type via any method
int i = 0;

Action<object> doSomething = (foo) => i += (int)foo.GetType().GetMethod("GetNumber").Invoke(foo, null);
var typedDoSomething = (typeof(Program)).GetMethod("DelegateHelper").MakeGenericMethod(fooType).Invoke(null, new object[] { doSomething });

var myFoo = Activator.CreateInstance(fooType);
fooType.GetMethod("UseFoo").Invoke(myFoo, new object[] { typedDoSomething });
Console.WriteLine(i);
}

public static Action<T> DelegateHelper<T>(Action<object> generic)
{
return x => generic(x);
}

基本上我需要使用一个通用的辅助方法来转换 Action<object>Action<T>在运行时确定

关于c# - 如何创建具有反射类型的委托(delegate)闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com