【发布时间】:2011-07-22 15:21:56
【问题描述】:
我想为使用基类作为类型要求的对象集合编写扩展方法。我知道这不一定是做事的最佳方式,但我很好奇,因为我有兴趣学习语言的细微差别。这个例子解释了我想做的事情。
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
我可以让扩展方法公开的唯一方法是创建人类集合。只要我只引用基类型的成员,是否可以在派生类型上调用这种类型的扩展方法?
【问题讨论】:
-
它适用于 .Net 4,但不适用于早期版本。问题上的标签说 c#3.0
标签: c# .net oop inheritance c#-3.0