在下面的代码中,我调用了扩展方法 [average] 三次。
首先是使用lambda,然后是使用匿名方法,第三次是通过委托。
使用委托的方式不起作用。有人能解释一下为什么吗?
非常感谢!
-----------代码--------------
使用委托的方式不起作用。有人能解释一下为什么吗?
非常感谢!
-----------代码--------------
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person> {
new Person { FirstName = "William", LastName = "Schokkele", Age = 35 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Hanne", LastName = "Schokkele", Age = 7 }
};
Person myPerson = new Person { FirstName = "Hanne", LastName = "Schokkele", Age = 7 };
myDelegate myDel = new myDelegate(myPerson.GetAge);
double averageAge= people.Average(p => p.Age);
double averageAge2 = people.Average(delegate(Person p) { return p.Age; });
double averageAge3 = people.Average(myDel); //THIS LINE DOESNT WORK. ERROR MESSAGE LIST<Person> does not contains a definition for 'average'
}
}
public delegate int myDelegate(Person p);
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int GetAge(Person p)
{
return p.Age;
}
}