[英]C# Covariance in Classes Implementing Common Interface
A WPF program I'm writing in C# has the following interface on the back-end: 我用C#编写的WPF程序在后端有以下接口:
public interface CatalogMenu<T> : CatalogItem where T : CatalogItem
{
void AddCatalogItem(T toAdd);
void RemoveCatalogItem(T toRemove);
List<T> AvailableCatalogItems { get; }
}
I have three classes that implement the interface, each with a different T. The problem is that I want to create a List<CatalogMenu<CatalogItem>>
to bind to a ListView, but this property in the View-Model doesn't compile... (thing1, thing2, and thing3 all implement the interface with a different T) 我有三个实现接口的类,每个类都有不同的T.问题是我想创建一个
List<CatalogMenu<CatalogItem>>
来绑定到ListView,但是View-Model中的这个属性不能编译。 ..(thing1,thing2和thing3都使用不同的T实现接口)
public List<CatalogMenu<CatalogItem>> MenuCategories
{
get
{
return new List<CatalogMenu<CatalogItem>>(){
ModuleCatalog.thing1,
ModuleCatalog.thing2,
ModuleCatalog.thing3
};
}
}
As much as I'd like it to, the compiler won't let me treat the "classes implementing CatalogMenu<T>
where T is a CatalogEntity" as a " CatalogMenu<CatalogItem>
". 根据我的意愿,编译器不会让我将“实现
CatalogMenu<T>
其中T是CatalogEntity)”视为“ CatalogMenu<CatalogItem>
”。 I want to present each class implementing the interface to the user through a common interface. 我想通过一个通用接口向用户展示实现接口的每个类。
If I left out any details, be a little patient with me; 如果我遗漏任何细节,请对我有点耐心; my head's spaghetti after reading about covariance for the last 30 minutes in an attempt to figure out a way to fix this.
在阅读了关于过去30分钟的协方差以试图找到解决方法的方法之后,我的头意粉。
.Net does not support covariant classes . .Net不支持协变类 。
If you add an ICatalogMenu<out T>
, you will be able to cast any CatalogMenu to ICatalogMenu<CatalogItem>
and put it into a List<ICatalogMenu<CatalogItem>>
如果添加
ICatalogMenu<out T>
,您将能够将任何CatalogMenu转换为ICatalogMenu<CatalogItem>
并将其放入List<ICatalogMenu<CatalogItem>>
You can accomplish the same effect using an ordinary non-generic interface or base class. 您可以使用普通的非泛型接口或基类来实现相同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.