2016-12-31 93 views
0

让说我有一个学生类代表必须是前主要方法

class Program 
{ 
    delegate bool del2(Student s); //I have to put this delegate before Main? 
    static void Main(string[] args) 
    { 
     List<Student> listStudent = new List<Student>() 
     { 
     ... //adding student instances... 
     }; 
     //delegate bool del2(Student s); Q1: why compile error if I put it here? 
     Predicate<Student> del1 = check; 
     Student s = listStudent.Find(del1); 
     Console.WriteLine("s is" + s.Name); 
    } 
    public static bool check(Student s) //Q2:why it need to be static method? 
    { 
     return s.Name == "Michael"; 
    } 
} 

我有两个问题:?

  1. 为什么我的主要方法之前把DEL2? del1是一个Predicate委托,我可以把它放在主要方法中,del2也是一个委托,为什么我不能把它放在主要方法里呢?

  2. 为什么检查方法是静态的?

+0

它是一种宣言。就像结构或类声明一样。 C#语法要求类型声明不会出现在方法体内。在Main()方法之后移动它*也很好,只是不在里面。 –

回答

0

简短的回答:

你应该申报的委托和谓语,因为它是在MSDN文档完成,因为关你当然应该。

龙答:

  1. 你不必把该委托主要前。你不能把它放在Main中。这是一个类型声明。那种类型(具有你声明的特定签名的代表)是用来传递函数作为参数的。你在main或其他方法中声明的东西在该方法的作用域内是有效的。即使你可以在一个方法中声明一个委托,这个签名也不会在其他任何地方被定义(并且是可识别的),这是无用的。

  2. 其实你分配到一个谓词不必是静态的方法,只是当你将它在那里。静态函数可用而不创建其类的实例。它们独立于该类别的对象。非静态方法属于它们的对象,并且它们专用于它们的对象。它们的具体目标代码是通过创建对象来创建的所以你可以使用一个非静态函数,如果一个可用的对象有它的话。说学生类有一个非静态的检查方法。你可以这样做:

    Student s2= new Student(); 
    Predicate<Student> del1 = s2.check; 
    
+0

谢谢你的回答。十分清晰。你能否也为我回答这个问题:http://stackoverflow.com/questions/41404219/multiple-class-inheritance-implication – grooveline

相关问题