我想为一个对象集合编写一个扩展方法,该方法使用基类作为类型要求。我知道这不一定是做事情的最佳方式,但我很好奇,因为我对语言的细微差别很感兴趣。这个例子解释了我想做的事情。
public class Human { public bool IsHappy { get; set; } }
public class Man : Human { public bool IsSurly { get; set; } }
public class Woman : Human { public bool IsAgreeable { get; set; } }
public static class ExtMethods
{
public static void HappinessStatus(this IEnumerable<Human> items)
{
foreach (Human item in items)
{
Console.WriteLine(item.IsHappy.ToString());
}
}
}
// then in some method, I wish to be able to do the following
List<Woman> females = RetreiveListElements(); // returns a list of Women
females.HappinessStatus(); // prints the happiness bool from each item in a collection
我唯一能够使扩展方法暴露的方式是创建一个Humans集合。只要我只引用基类型的成员,就可以在派生类型上调用这种类型的扩展方法吗?