简体   繁体   English

C#-为什么我可以在未实例化的类中使用委托?

[英]C# - How come I can use delegates in the class that was not instantiated?

I thought that delegate fields are just like other fields and that I cannot use them until the class is instantiated. 我认为委托字段与其他字段一样,并且在实例化该类之前我无法使用它们。 However: 然而:

 class Program
    {

        delegate void lol (int A);
         string myX;

        static void Main(string[] args)
        {
            lol x = ... //works     

            myX //does not exist, 
        }
    }
delegate void lol (int A);

A Delegate is not a field it is a "Nested Type", So you can use it just like any other types. 委托不是字段,而是“嵌套类型”,因此您可以像使用其他任何类型一样使用它。

And refering to myX inside the Main is illegal because myX is instance field. 而指的myX里面Main是非法的,因为myX是实例字段。 you need to use instance.myX to use it inside a static method( Main() here ) 您需要使用instance.myX在静态方法( Main() here )中使用它

To be more clear, Try the following you'll realize what you're doing wrong 更清楚地说,请尝试以下操作,您将发现自己在做什么错

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, 
    }
}

A delegate instance is an object that refers to one or more target methods. 委托实例是引用一个或多个目标方法的对象。

lol x = ... THIS WILL CREATE DELEGATE INSTANCE 大声笑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, 
    }
}

Another importent delegate Syntaxis I have copied for you from MSDN 我已经从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); };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM