[英]C# Casting object with inner generic
I'm trying to cast a concrete class with generics to its interfaces and getting an error. 我正在尝试将具有泛型的具体类转换为其接口并获取错误。 I'm not sure what I'm missing. 我不确定我错过了什么。 I need to get them into the common type. 我需要让他们进入普通类型。
Unable to cast object of type 'HierarchalLocationFilterSet' to type 'ImAFilterSet`1[ModelBase]'. 无法将“HierarchalLocationFilterSet”类型的对象强制转换为“ImAFilterSet`1 [ModelBase]”。
Everything compiles and runs, I just cant seem to do something like below. 一切都在编译和运行,我似乎无法做下面的事情。
ImAFilterSet<IModelBase> c = new HierarchalLocationFilterSet()
I can go half way ok 我可以走到一半
var thisWorks = c as FilterSetBase<LocationModel>;
var thisAlsoWorks = c as ImAFilterSet<LocationModel>;
//This is a hard fail
var x = ((ImAFilterSet<ModelBase>) c );
var y = ((ImAFilterSet<IModelBase>) c );
Given 特定
public interface ImAFilterSet<C> where C : IModelBase
{
List<C> Children { get; set; }
}
public abstract class FilterSetBase<C> : ImAFilterSet<C> where C : IModelBase
public class HierarchalLocationFilterSet : FilterSetBase<LocationModel>
public class LocationModel : ModelBase
public abstract class ModelBase : IModelBase
Thanks! 谢谢!
Generic classes/interfaces are invariant by default in .NET. 默认情况下,.NET中的泛型类/接口是不变的。 That's why your code fails. 这就是你的代码失败的原因。
To cast FilterSetBase<T1>
to ImAFilterSet<T2>
T1
has to be the same T2
. 要将FilterSetBase<T1>
为ImAFilterSet<T2>
T1
必须与T2
相同。 Having T1
inherit T2
is not enough. T1
继承T2
是不够的。
You can fix that by changing declaration of FilterSetBase<C>
: 您可以通过更改FilterSetBase<C>
声明来解决此问题:
public abstract class FilterSetBase<C> : ImAFilterSet<IModelBase>
where C : IModelBase { }
or you can make ImAFilterSet
covariant: 或者你可以使ImAFilterSet
协变:
public interface ImAFilterSet<out C>
where C : IModelBase { }
That's only possible when your interface doesn't declare any methods/properties with argument typed as C
. 只有当您的接口没有声明任何类型为C
参数的方法/属性时,才有可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.