且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法保存的方法在变量后来打电话吗?如果我的方法返回不同类型的?

更新时间:2022-11-24 15:54:18

好了,你可以这样做:

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();
}