是否有一种方法可以将方法保存在变量中,然后再调用它?如果我的方法返回不同的类型
本文关键字:方法 如果 调用 然后 我的 类型 返回 变量 一种 存在 是否 | 更新日期: 2023-09-27 18:02:00
编辑:谢谢你的回答。我目前正在努力!!'
我有3个方法,S()返回string, D()返回double, B()返回bool。
我也有一个变量来决定我使用哪个方法。我想这样做:
// 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();
}
这可能吗?
我读了这篇文章:在c#中将方法存储为类的成员变量但是我需要存储不同返回类型的方法…
你可以这样做:
Delegate method;
...
if (choice == "D") // Consider using a switch...
{
method = (Func<double>) D;
}
那么DoSomething
将被声明为Delegate
,这不是很好。
另一种选择是将方法包装在一个委托中,该委托只执行所需的转换以获得返回值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();
}
Func<object> method;
var choice = "D";
if(choice=="D")
{
method = () => (object)D;
}
else if(choice=="B")
{
method = () => (object)B;
}
else if(choice=="S")
{
method = () => (object)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();
}
private delegate int MyDelegate();
private MyDelegate 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);