[英]c# methods that takes an Interface?
我是界面的新手。
我有很多对象作为DTO通过我的图层传递到UI。 它们中的一些非常复杂(有一些属性),但是在某些情况下,我只想在DropDown列表中使用它们。 这些DTO都有一个int Id
和一个string Description
。
我想创建一个静态函数,该函数接受这些对象之一的List<>
,并返回List<SelectListItem>
因此,我尝试第一次使用接口。
我创建了一个接口:
public interface IListableItem
{
int Id { get; set; }
string Description { get; set; }
}
然后,我将该接口分配给我要转换的DTO对象之一:
public class CategoryDto : BaseDto , IListableItem
{
public int PortfolioId { get; set; }
public string Description { get; set; }
public List<ExtendedSubCategoryDto> SubCategories { get; set; }
public bool IsExpenseCategory { get; set; }
public CategoryDto()
{
SubCategories = new List<ExtendedSubCategoryDto>();
}
}
然后,我创建了一个通用方法,该方法采用了dtos类别的列表,并有望返回一个列表
public static List<SelectListItem> TranslateToSelectList(List<IListableItem> source)
{
var reply = source.Select(item => new SelectListItem
{
Value = item.Id.ToString(CultureInfo.InvariantCulture), Text = item.Description
}).ToList();
return reply;
}
但是,当我尝试使用此方法,将其传递给List时,它将失败。
model.Categories =
Translator.TranslateToSelectList(MyService.GetCategoriesByPortfolioId());
GetCategoriesByPortfolioId返回一个列表。
错误失败:
无法将CategoryDto分配给IListableItem
就我而言,这可能是一个基本的界面理解问题,但是我做错了什么,该如何解决?
如果您的方法需要List<IListableItem>
,则不能传递List<CategoryDTO>
。
如果可能的话,可以Add
实现IListableItem
接口的元素的不同实例Add
到保存CategoryDTO
元素的集合中,然后读取它们。
最终,这没有任何意义。
如果使用IEnumerable
接口,则可以修复它。 这允许协方差(在泛型类型参数中从较高的类型到较低的类型) 。
之所以起作用,是因为IEnumerable
是collection的“只读视图”,因此您无法真正向其添加任何内容-再加上重要的一点, type parameter
被标记为covariant 。
public static List<SelectListItem> TranslateToSelectList(
IEnumerable<IListableItem> source)
{..}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.