首页 > 解决方案 > 使用父属性调用父方法

问题描述

我想创建一个排序功能。

public class Program 
{
    public static void Main() 
    {
        // the error is here
        Child1.SortList(new List<Child1>() {});
    }
}

public class Parent
{
    public string Code { get; set; }
    public Nullable<decimal> Order { get; set; }
    public DateTime DateBegin { get; set; }
    public Nullable<DateTime> DateEnd { get; set; }

    public static List<Parent> SortList(List<Parent> list)
    {
        return list
            .Where(x => 
                   DateTime.Compare(x.DateBegin, DateTime.Today) <= 0 && 
                   (
                       x.DateEnd == null || 
                       DateTime.Compare((DateTime)x.DateEnd, DateTime.Today) > 0))
            .OrderBy(x => x.Order)
            .ToList();
    }
}

public class Child1 : Parent
{
    public string Description { get; set; }
}

当我打电话时SortList(),我收到一个错误,无法转换Child1Parent. 我不知道如何实现接口或T?

标签: c#

解决方案


C# 列表不是协变的。您可以改用IEnumerable它,它是协变的。

List<string> strings = new List<string>();

IEnumerable<object> objects = strings; // this does work
List<object> objectList = strings; // this does not work

这是对您有用的简化版本。

public class Program
{
    public static void Main()
    {
        Child1.SortList(new List<Child1>() {});
    }
}

public class Parent
{
    public static List<Parent> SortList(IEnumerable<Parent> list)
    {
        // et cetera
    }
}

public class Child1 : Parent { }

推荐阅读