和匿名方法一样,我使用"delegate“关键字声明的委托也是匿名委托吗?
namespace Test
{
public delegate void MyDelegate();
class Program
{
static void Main(string[] args)
{
DelegateTest tst = new DelegateTest();
tst.Chaining();
Console.ReadKey(true);
}
}
class DelegateTest
{
public event MyDelegate del;
public void Chaining()
{
del += delegate { Console.WriteLine("Hello World"); };
del += delegate { Console.WriteLine("Good Things"); };
del += delegate { Console.WriteLine("Wonderful World"); };
del();
}
}
}
发布于 2009-11-17 21:03:44
示例中的委托集合指向许多匿名方法。委托“只是一个方法指针”。无论它指向的是真实方法还是匿名方法,都没有关系。
请参阅http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx
发布于 2009-11-17 21:07:28
这是正确的,您已经为一个事件分配了许多匿名方法。
如果您使用的是较新版本的c#,也可以使用lambda执行类似的操作。例如:
class DelegateTest
{
public event Action del;
public void Chaining()
{
del += () => Console.WriteLine("Hello World");
del += () => Console.WriteLine("Good Things");
del += () => Console.WriteLine("Wonderful World");
del();
}
}
发布于 2009-11-17 21:03:20
是的,它们是匿名委托(或者,更具体地说,是delegates calling an anonymous method。
https://stackoverflow.com/questions/1748719
复制相似问题