[英]Cast unknown object to generic interface of interface (from initially explicit generic type of generic collection type of type)
基本上我得到了那些示例类:
public interface IHasParts<TCollectionType> : where TCollectionType : ICollection
{
TCollectionType Parts { get; set; }
}
public class CarPart
{
//...
}
public class Car : IHasParts<List<CarPart>>
{
public List<CarPart> Parts { get; set; }
//...
}
是的,我需要在这里使用ICollection
的通用接口,因为实现IHasParts的类需要基于某些硬编程条件的不同列表类型的Parts
。
现在我得到了一个未知的对象,即Car
,我需要将它转换为仍然具有Parts
属性的最高父级:
Car c = new Car() {
Parts = new List<CarPart>() {
// ...
}
};
object o = (object)c;
int partsCount = ((IHasParts<ICollection>)o).Parts.Count; // InvalidCastException
我怎样才能做到这一点? DotNetFiddle
这是一个差异问题。
你假设,因为List<T>
是ICollection
的子类型,那么IHasParts<List<T>>
必须是IHasParts<ICollection>
的子类型。 它没有。
如果您希望IHasParts<A>
是IHasParts<B>
的子类型,其中A
是B
的子类型,那么您需要在其类型参数T
(使用out
关键字)中使IHasParts
协变 。
public interface IHasParts<out TCollectionType> : where TCollectionType : ICollection
{
TCollectionType Parts { get; }
}
对于要协变的类型, T
只能用于协变位置 :方法返回类型,只获取属性类型和只获取索引器。
它不能再用于逆变位置:方法参数,属性/索引器设置器。
如果使用ICollection
而不是List<CarPart>
定义Car类,则可以:
public class Car : IHasParts<ICollection>
{
public ICollection Parts { get; set; }
}
您仍然可以使用List<CarPart>
初始化零件
添加一个抽象类来处理指定ICollection类型。 声明你的代码是这样的:
public interface IHasParts
{
ICollection Parts { get; }
}
public abstract class HasParts<TCollectionType, TPartType> : IHasParts where TCollectionType : ICollection
{
public TCollectionType Parts;
ICollection IHasParts.Parts { get { return this.Parts; } }
}
public class CarPart
{
//...
}
public class Car : HasParts<List<CarPart>, CarPart>
{
protected void AddParts()
{
this.Parts.Add(new CarPart());
}
}
更新:
这是您的DotNetFiddle的更新版本: https ://dotnetfiddle.net/O3JZgc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.