方法签名中具有基类型的派生类型集合的扩展方法

Nat*_*ate 3 .net c# oop inheritance c#-3.0

我想为使用基类作为类型要求的对象集合编写扩展方法.我知道这不一定是做事的最佳方式,但我很好奇,因为我有兴趣学习语言的细微差别.这个例子解释了我想做什么.

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
Run Code Online (Sandbox Code Playgroud)

我可以让扩展方法暴露的唯一方法是创建一个人类集合.是否可以在派生类型上调用此类型的扩展方法,只要我只引用基类型的成员?

Bol*_*ock 6

您的代码实际上将使用C#4编译器进行编译,因为该版本支持逆变类型参数.

为了使它能够使用C#3,您可以IEnumerable<T>使用where T : Human作用于泛型类型的约束创建通用扩展方法,而不是仅用于IEnumerable<Human>:

public static void HappinessStatus<T>(this IEnumerable<T> items) where T : Human
{
    foreach (T item in items)
    {
        Console.WriteLine(item.IsHappy.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以List<Woman>按照描述调用集合上的扩展方法.