有没有办法保存的方法在变量后来打电话吗?如果我的方法返回不同类型的? [英] Is there a way to save a method in a variable then call it later? What if my methods return different types?
问题描述
编辑:谢谢你的答案。我目前的工作就可以了!\
Thank you for the answers. I am currently working on it!!\
我有3个方法,S()返回字符串,D()返回双和B()返回布尔。
I have 3 methods, S() returns string, D() returns double and B() returns bool.
我也有我决定使用哪种方法的变量。
我想做到这一点:
I also have a variable that decides which method I use. I want do this:
// I tried Func<object> method; but it says D() and B() don't return object.
// Is there a way to use Delegate method; ? That gives me an eror saying method group is not type System.Delegate
var method;
var choice = "D";
if(choice=="D")
{
method = D;
}
else if(choice=="B")
{
method = B;
}
else if(choice=="S")
{
method = S;
}
else return;
DoSomething(method); // call another method using the method as a delegate.
// or instead of calling another method, I want to do:
for(int i = 0; i < 20; i++){
SomeArray[i] = method();
}
这可能吗?
Is this possible?
我看了这个帖子:
的存储的方法,在C#中
类的成员变量,但我需要存储与不同的返回类型...
I read this post: Storing a Method as a Member Variable of a Class in C# But I need to store methods with different return types...
推荐答案
好了,你可以这样做:
Delegate method;
...
if (choice == "D") // Consider using a switch...
{
method = (Func<double>) D;
}
然后的DoSomething
会被宣布为刚代表
,这还不是特别好的。
Then DoSomething
would be declared as just Delegate
, which isn't terribly nice.
另外,也可以来包装方法刚刚进行任何转换的委托要求得到返回值对象
:
Another alternative would be to wrap the method in a delegate which just performs whatever conversion is required to get the return value as object
:
Func<object> method;
...
if (choice == "D") // Consider using a switch...
{
method = BuildMethod(D);
}
...
// Wrap an existing delegate in another one
static Func<object> BuildMethod<T>(Func<T> func)
{
return () => func();
}
这篇关于有没有办法保存的方法在变量后来打电话吗?如果我的方法返回不同类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!