是否有理由使用此:
bool flag;
public Form1()
{
if (flag) byDelegate = square;
else byDelegate = cube;
Text = byDelegate(3).ToString();
}
int square(int i) { return i * i; }
int cube(int i) { return i * i * i; }
delegate int delegate1(int x);
delegate1 byDelegate;
Run Code Online (Sandbox Code Playgroud)
而不是:
bool flag;
public Form2()
{
Text = fakeDelegate(3).ToString();
}
int square(int i) { return i * i; }
int cube(int i) { return i * i * i; }
int fakeDelegate(int i)
{
if (flag) return square(i);
else return cube(i);
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
委托通常异步使用,用于事件或传递给方法/类型,以便委托指向的方法('函数指针')可以在以后调用.在你的情况下,看起来没有优势,因为你正在同步地做所有事情.
例如
private Action<double> _performWhenFinished.
public Form1(Action<double> performWhenFinished)
{
_performWhenFinished = performWhenFinished;
}
public void CalculatePi()
{
double pie = 0d;
// Create a new thread, take 2 minutes to perform the task
// Thread.Wait etc., then and run your delegate
_performWhenFinished(pie);
}
Run Code Online (Sandbox Code Playgroud)
除非您希望代码通过这些声明提供更多含义,否则通常不需要在3.5以上声明自己的委托.该Action
类型和Func
类型(FUNC提供了一个返回值的方法),节省您的精力.