类内的代理的默认值 [英] Default value of delegates inside classes
问题描述
using System;
public delegate void Printer(string s);
class Program
{
public static void Main(string[] args)
{
Printer p = new Printer(delegate {});
p+= myPrint;
p("Hello");
Console.ReadKey(true);
}
public static void myPrint(string s)
{
System.Console.WriteLine(s);
}
}
好像我必须初始化一个委托一个空的匿名函数,以便能够使用 + =
。当我省略新的
子句时, p
将被 null
和 + =
不起作用,这是有道理的。
It seems as if I have to initialize a delegate with an empty anonymous function to be able to use +=
later on. When I omit the new
clause, p
gets to be null
and +=
doesn't work, which makes sense.
现在,当我有一个类代理实例,我可以执行以下操作:
Now, when I have a class with a delegate instance, I can do the following:
using System;
public delegate void Printer(string s);
class Program
{
public static void Main(string[] args)
{
A a = new A();
a.p += myPrint;
a.p("Hello");
Console.ReadKey(true);
}
public static void myPrint(string s)
{
System.Console.WriteLine(s);
}
}
class A {
public Printer p;
}
为什么允许这样做?代理实例有一个默认值 p
?它不能是 null
,因为我将无法使用 + =
为它分配一个新的回调。我试图通过关键字代理的默认值
搜索这个问题,没有发现任何内容。另外,如果问题是否太基础,对不起。
Why is this allowed? Is there a default value for the delegate instance p
? It can't be null
because then I would not be able to assign it a new callback using +=
. I have tried to search for this problem with the keywords "default value for delegates"
and found nothing. Also, sorry if the question if too basic.
感谢您的帮助!
推荐答案
代理是引用类型,因此默认值为 null
。
但是,变量字段)不会默认初始化:
However, variables (unlike fields) are not initialized by default:
Printer p;
p += myPrint; // doesn't work: uninitialized variable
您需要初始化变量才能使用它:
You need to initialize the variable before you can use it:
Printer p = null;
p += myPrint;
或
Printer p;
p = null;
p += myPrint;
请注意,对于代表(但不是事件!)
Note that for delegates (but not events!)
p += myPrint;
是
p = (Printer)Delegate.Combine(p, new Printer(myPrint));
这篇关于类内的代理的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!