具有内部泛型的C#转换对象
作者:互联网
我正在尝试将具有泛型的具体类转换为其接口并出现错误.我不确定我缺少什么.我需要使它们成为普通类型.
Unable to cast object of type ‘HierarchalLocationFilterSet’ to type ‘ImAFilterSet`1[ModelBase]’.
一切都可以编译并运行,我似乎无法执行以下操作.
ImAFilterSet<IModelBase> c = new HierarchalLocationFilterSet()
我可以走一半
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 );
给定
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
谢谢!
解决方法:
通用类/接口在.NET中默认是不变的.这就是您的代码失败的原因.
投射FilterSetBase< T1>到ImAFilterSet< T2>. T1必须与T2相同.让T1继承T2是不够的.
您可以通过更改FilterSetBase< C>的声明来解决此问题:
public abstract class FilterSetBase<C> : ImAFilterSet<IModelBase>
where C : IModelBase { }
或者您可以使ImAFilterSet成为协变量:
public interface ImAFilterSet<out C>
where C : IModelBase { }
仅当您的接口未声明参数类型为C的任何方法/属性时,这才可能.
标签:casting,generics,c 来源: https://codeday.me/bug/20191120/2045250.html