2013-10-14 35 views

回答

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

嵌套类型也是类中的一个类... – user970696

+0

是的,它意味着一个类型内的类型,类 - >类,类 - >结构,类 - >委托,结构 - >结构,结构 - >委托等 –

+0

不要误解我的意思,我知道如何使用委托或lambda表达式,我只是意识到我不知道我不需要程序类的实例(在这种情况下)。我总是把代表作为另一个客体。字符串,int也是类型(数据类型)。 – user970696

-1

委托实例一个引用一个或多个目标方法的对象。

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

另一个importent委托大成我已经从MSDN

// 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); }; 
相关问题