方法签名中具有基本类型的派生类型集合的扩展方法 [英] Extension Method for a Collection of Derived Types with Base Type in Method Signature
问题描述
我想为使用基类作为类型要求的对象集合编写扩展方法.我了解这不一定是做事的最佳方法,但我很好奇,因为我有兴趣学习语言的细微差别.这个例子说明了我想做什么.
I want to write an extension method for a collection of objects that uses base class as a type requirement. I understand this is not necessarily the best way to do things, but I am curious because I'm interested in learning the nuances of the language. This example explains what I would like to do.
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集合.只要我仅引用基本类型的成员,就可以在派生类型上调用这种扩展方法吗?
The only way I can get the extension method to expose is to create a collection of Humans. Is it possible to call this type of extension method on derived types as long as I only reference members of the base type?
推荐答案
Your code will actually compile as is with the C# 4 compiler, as that version supports contravariant type parameters.
要使其与C#3配合使用,您可以为 IEnumerable< T>
创建通用扩展方法,并具有对通用类型起作用的 where T:Human
约束,而不是专门用于 IEnumerable< Human>
:
To get it working with C# 3, you can create a generic extension method for IEnumerable<T>
with a where T : Human
constraint that acts on the generic type, instead of specifically only for IEnumerable<Human>
:
public static void HappinessStatus<T>(this IEnumerable<T> items) where T : Human
{
foreach (T item in items)
{
Console.WriteLine(item.IsHappy.ToString());
}
}
然后,您可以按照自己的描述在 List< Woman>
集合上调用扩展方法.
Then you can call the extension method on your List<Woman>
collection as you describe.
这篇关于方法签名中具有基本类型的派生类型集合的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!