c# - 使用父属性调用父方法
问题描述
我想创建一个排序功能。
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()
,我收到一个错误,无法转换Child1
为Parent
. 我不知道如何实现接口或T?
解决方案
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 { }
推荐阅读
- python - 使用 AWS Lambda 错误将文件写入 S3 - 调用 PutObject 操作时发生错误 (AccessDenied):访问被拒绝
- android - Litho Radio Group 容器
- c# - 如何对 dotnet core Entity Framework 中的许多表中的数据进行分组
- java - 如何正确取消关联任务(作为可执行脚本)?
- azure - ADF / 将 csv 表转换为 json
- android - 从styles.xml切换应用主题时,有没有办法改变项目的可见性?
- amazon-web-services - 使用 AWS CLI 时发布的错误中更新 cloudformation 堆栈时出现回滚错误
- flutter - 'positions.isNotEmpty':PageController.page 在使用它构建 PageView 之前无法访问。旋转木马颤动
- python - Python seaborn.heatmap 手动定义类别
- javascript - 使用 setFocus 更改 jVectorMap 中多个区域的缩放级别