简体   繁体   English

C#任何函数作为参数

[英]C# Any function as parameter

Is it possible to created a method that takes ANY method (regardless of it's parameters) as a parameter? 是否可以创建一个方法,将任何方法(不管它的参数)作为参数? The method would also have a params parameter which then takes all the parameters for the parameter-method. 该方法还将具有params参数,该参数然后获取参数方法的所有参数。

So basically what I want is something like this: 基本上我想要的是这样的:

public void CallTheMethod(Action<int> theMethod, params object[] parameters)

But then for any method, not just for methods that takes an int. 但是对于任何方法,不仅仅是采用int的方法。

Is something like this possible? 这样的事情可能吗?

Thanks 谢谢

Yes, with a delegate: 是的,有代表:

public object CallTheMethod(Delegate theMethod, params object[] parameters)
{
    return theMethod.DynamicInvoke(parameters);
}

But see Marc Gravell's comment on your question :) 但请参阅Marc Gravell对您问题的评论 :)

Well, you could pass the non-specific Delegate , but DynamicInvoke is sloooooowwwwww (relatively speaking) 好吧,你可以通过非特定的Delegate ,但DynamicInvokesloooooowwwwww (相对来说)

It's possible, but not what should be done. 这是可能的,但不应该做什么。

This is what I would do: 这就是我要做的:

public void CallTheMethod(Action toCall)

You might go "huh". 你可能会去“嗯”。 Basically, what it lets the user do is this: 基本上,它让用户做的是:

CallTheMethod(() => SomeOtherMethod(with, some, other, parameters));

However, if you want it to return a type, it involves generics: 但是,如果您希望它返回一个类型,则涉及泛型:

public void CallTheMethod<T>(Func<T> theMethod)

You can put generic constraints on that type, do whatever you want with it, etc. 您可以在该类型上放置通用约束,随意执行任何操作,等等。

Yes. 是。 You can use DynamicInvoke to call the methods: 您可以使用DynamicInvoke来调用方法:

Action<int> method1 = i => { };
Func<bool, string> method2 = b => "Hello";

int arg1 = 3;
bool arg2 = true;
//return type is void, so result = null;
object result = method1.DynamicInvoke(arg1);

//result now becomes "Hello";
result = method2.DynamicInvoke(arg2);

A method to do this would become: 执行此操作的方法将变为:

object InvokeMyMethod(Delegate method, params object[] args)
{
    return method.DynamicInvoke(args);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM