使用和不使用 Invoke 有什么区别?
What's the difference of using and not using Invoke?
我对使用和不使用 Invoke 感到困惑。
在下面的例子中,我看不出有什么不同
int answer = b(10, 10);
和
int answer = b.Invoke(10, 10);
谁能帮我解决这个问题?
谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TEST
{
public delegate int BinaryOp(int x, int y);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
BinaryOp b = new BinaryOp(add);
//int answer = b(10, 10);
int answer = b.Invoke(10, 10);
Console.WriteLine("Doing more work in Main");
Console.WriteLine("10 + 10 is {0}", answer);
Console.Read();
}
static int add(int x, int y)
{
Console.WriteLine("add innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
return x + y;
}
}
}
基本上没有区别
特别是因为 Delegate
不是真正的函数而是函数的持有者,所以持有该函数的 class 必须有某种方式来调用它。因此,方法 Invoke
。另一方面,当您将括号附加到 Delegate
时,编译器足够聪明,可以自动调用 Invoke
。参见 https://jacksondunstan.com/articles/3283。
我对使用和不使用 Invoke 感到困惑。
在下面的例子中,我看不出有什么不同
int answer = b(10, 10);
和
int answer = b.Invoke(10, 10);
谁能帮我解决这个问题? 谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TEST
{
public delegate int BinaryOp(int x, int y);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
BinaryOp b = new BinaryOp(add);
//int answer = b(10, 10);
int answer = b.Invoke(10, 10);
Console.WriteLine("Doing more work in Main");
Console.WriteLine("10 + 10 is {0}", answer);
Console.Read();
}
static int add(int x, int y)
{
Console.WriteLine("add innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
return x + y;
}
}
}
基本上没有区别
特别是因为 Delegate
不是真正的函数而是函数的持有者,所以持有该函数的 class 必须有某种方式来调用它。因此,方法 Invoke
。另一方面,当您将括号附加到 Delegate
时,编译器足够聪明,可以自动调用 Invoke
。参见 https://jacksondunstan.com/articles/3283。