如何将方法名称传递给另一个方法并通过委托变量调用它?
我有一个方法,其中包含指向另一个类的委托变量。 我想通过此委托调用该类中的方法,但将该方法的名称作为字符串传递给包含该委托的方法。
这怎么能做到呢?使用反射? 功能
?
编辑:
我现在明白反射可能不是最好的解决方案。
这就是我所拥有的:
private static void MethodContainingDelegate(string methodNameInOtherClassAsString)
{
_listOfSub.ForEach(delegate(Callback callback)
{
//Here the first works, but I want the method to be general and
// therefore pass the method name as a string, not specfify it.
callback.MethodNameInOtherClass();
//This below is what I am trying to get to work.
callback.MethodNameInOtherClassAsString();
}
});
}
所以,基本上,我正在寻找一种方法让我的回调委托“识别”我的 methodNameInOtherClassAsString 实际上是在另一个类中执行的方法。
谢谢!
I have a method that contains a delegate variable that points at another class.
I want to call a method in that class via this delegate, but pass the name of the method as a string to the method containing the delegate.
How can this be done? Using reflection? Func<T>
?
Edit:
I understand now that reflection may not be the best solution.
This is what I have:
private static void MethodContainingDelegate(string methodNameInOtherClassAsString)
{
_listOfSub.ForEach(delegate(Callback callback)
{
//Here the first works, but I want the method to be general and
// therefore pass the method name as a string, not specfify it.
callback.MethodNameInOtherClass();
//This below is what I am trying to get to work.
callback.MethodNameInOtherClassAsString();
}
});
}
So, basically, I am looking for a way to make my callback delegate "recognize" that my methodNameInOtherClassAsString is actually a method to execute in the other class.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很简单:
委托变量指向什么类并不重要。它可以在另一个类中定义——没有太大区别。
我认为您甚至可以从委托变量本身查询原始方法的名称,而无需反射。每个委托都有一个名为
Method
的属性,专门用于此目的。It's very simple:
It doesn't matter, what class does the delegate variable point to. It can be defined in another class -- there's not much difference.
I think you could even query the name of the original method from the delegate variable itself without reflection. Every delegate has a property called
Method
exactly for that.您可以执行以下操作:
其中 Foo 是您的目标类,Bar 是您要调用的方法。
但你应该注意到,反射会对你的程序的性能产生很大的影响。考虑改用强类型委托。
You can do something like this:
Where Foo is your target class, Bar is the method you want to call.
But you should note that reflection will have a great impact on your program's performance. Consider using strongly typed delegates instead.
假设您有方法名称的字符串表示形式:
显然您需要为此添加一些错误检查,并且应该使用更具体的版本 GetMethod 如果可以的话。
Assuming you have string representation of the method name:
you need to add some error checking to this obviously, and should use a more specific version of GetMethod if you can.