使用Reflection Invoke将Lamba作为参数传递的静态泛型方法

Nik*_*nis 1 c# reflection lambda fakeiteasy

是否可以通过Reflection编写以下代码?

    var fake = A.Fake<Foo>(
            o => o.WithArgumentsForConstructor(new[] { "Hello" }));
Run Code Online (Sandbox Code Playgroud)

其中Ø为:

Action<IFakeOptionsBuilder<T>>
Run Code Online (Sandbox Code Playgroud)

其中WithArgumentsForConstructor是:

IFakeOptionsBuilder<T> WithArgumentsForConstructor(IEnumerable<object> argumentsForConstructor);
Run Code Online (Sandbox Code Playgroud)

Foo类是:

class Foo
{
    public Foo(string s)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我做的是:

object fake = typeof(A)
    .GetMethod("Fake", new Type[] { })
    .MakeGenericMethod(new[] { this.targetType })
    .Invoke(null, /* Here I need to pass the lambda. */);
Run Code Online (Sandbox Code Playgroud)

Pat*_*gne 5

是的,可以通过反思做你的建议,但是非常不必要.像这样自己定义一个静态方法会更简单:

public static class MyClass
{
    public static T CreateFakeWithArgumentsForConstructor<T>(object[] argumentsForConstructor)
    {
        return A.Fake<T>(x => x.WithArgumentsForConstructor(argumentsForConstructor));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在只需使用反射调用此函数:

var method = typeof(MyClass).GetMethod("CreateFakeWithArgumentsForConstructor", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new[] { theType });
method.Invoke(null, argumentsForConstructor);
Run Code Online (Sandbox Code Playgroud)