我认为委托字段就像其他字段一样,在实例化类之前我不能使用它们。但是:
class Program
{
delegate void lol (int A);
string myX;
static void Main(string[] args)
{
lol x = ... //works
myX //does not exist,
}
}
答案 0 :(得分:6)
delegate void lol (int A);
委托不是一个字段,它是一个“嵌套类型”,所以你可以像任何其他类型一样使用它。
在myX
中引用Main
是非法的,因为myX
是实例字段。你需要使用instance.myX在静态方法(Main() here
)
更清楚一点,试试以下你会意识到你做错了什么
class Program
{
delegate void lol (int A);
string myX;
lol l;
static void Main(string[] args)
{
l = null; //does not exist
myX //does not exist,
}
}
答案 1 :(得分:-1)
委托实例是引用一个或多个目标方法的对象。
lol x = ...这将创建代表实例
class Program
{
delegate void lol (int A);
string myX;
static void Main(string[] args)
{
lol x = ... // THIS WILL CREATE DELEGATE INSTANCE
x(3) // THIS WILL INVOKE THE DELEGATE
myX //does not exist,
}
}
我从MSDN
为您复制的另一个重要委托语法Syntaxis // Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };