【发布时间】:2011-10-05 10:47:27
【问题描述】:
编辑:感谢您的回答。我目前正在努力!\
我有3个方法,S()返回字符串,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();
}
这可能吗?
我读了这篇文章: Storing a Method as a Member Variable of a Class in C# 但是我需要存储具有不同返回类型的方法...
【问题讨论】:
-
我很感兴趣,你为什么要传递一个方法而不是在一个你可以按需访问的范围内声明它?
-
其实我需要的方法是静态的,所以可以访问。只是我需要根据选择中的值选择一个来使用,而不是每次通过循环都对选择进行 if-elseif 检查。
-
您需要实际声明一个委托。这将允许您在 C# 中模拟函数指针,就像在 C 或 C++ 中找到它们一样。