C#:将具有派生接口的通用对象向下转换到基本接口 [英] C# : Downcasting Generic object with derived interfaces to the base interface
问题描述
我具有以下对象体系结构:
I have the following object architecture :
public interface IConfigAlarmBase{}
public interface IConfigAlarmBinary:IConfigAlarmBase{}
public interface IConfigAlarmRanged:IConfigAlarmBase{}
public interface IAlarmItem<TConfig> where TConfig : IConfigAlarmBase{}
public abstract class AlarmItemBase<TConfig> : IAlarmItem<TConfig> where TConfig :IConfigAlarmBase {}
public abstract class AlarmItemBinaryBase:AlarmItemBase<IConfigAlarmBinary>{}
public abstract class AlarmItemRangedBase<TConfig> : AlarmItemBase<TConfig> where TConfig:IConfigAlarmRanged{}
public class AlarmImplementation:AlarmItemRangedBase<IConfigAlarmRanged>
然后是 AlarmItemBinaryBase
对象及其兄弟 AlarmItemRangedBase
的一些实现.
And then there are some implementations of the AlarmItemBinaryBase
object and its brother the AlarmItemRangedBase
.
我想将所有警报存储在一个列表中,该列表定义为: List< IAlarmItem< IConfigAlarmBase>>
I wanted to store all my alarms in a single list that would be defined as : List<IAlarmItem<IConfigAlarmBase>>
但是当我实例化列表并尝试填充它时,我得到一个错误:
But when I instantiate my list and try to fill it I get an error:
System.InvalidCastException: Unable to cast object of type 'Alarm.Implementations.AlarmImplementation' to type 'Common.Application.Alarm.IAlarmItem`1[Common.Config.Alarms.IConfigAlarmBase]'.
我不理解,因为 AlarmImplementation
是 IAlarmItem
的实现(通过 AlarmItemRangedBase
的类层次结构)和 IConfigAlarmRanged
是 IConfigAlarmBase
的子级.对我来说,这应该是一种沮丧,因为所有类都是从基础类派生的.
Which I don't understand as the AlarmImplementation
is an implementation of IAlarmItem
(through the class hierarchy of the AlarmItemRangedBase
) and the IConfigAlarmRanged
is a child of the IConfigAlarmBase
. To me this was supposed to be a downcast as all the classes are derived from the Base one.
但是看来我错了.当编译器替换模板时,是否有可能将通用类型视为特定类型,而忽略了模板化类型之间的关系?
But it seems I'm wrong. Would it be possible that when the compiler replace the templates it then consider the generic type as specific type ignoring the relationships between the templated types ?
感谢您考虑这个问题.
推荐答案
您的列表是 List< IAlarmItem< IConfigAlarmBase>>
,然后尝试添加 AlarmItemRangedBase< IConfigAlarmRanged>
,因此即使 IConfigAlarmRanged
从 IConfigAlarmBase
继承,您也会有类型不匹配的情况,因为 IAlarmItem< IConfigAlarmBase>
和 IAlarmItem< IConfigAlarmRanged>
不是同一类型:它们是两个截然不同的封闭构造的泛型类型,您不能从一个类型转换为另一个类型.
Your list is List<IAlarmItem<IConfigAlarmBase>>
and you try to add an AlarmItemRangedBase<IConfigAlarmRanged>
, so you have type mismatch even if IConfigAlarmRanged
inherits from IConfigAlarmBase
because IAlarmItem<IConfigAlarmBase>
and IAlarmItem<IConfigAlarmRanged>
are not the same type : they are two distinct closed constructed generic types and you can't cast from one to the other.
例如, List< string>
和 List< int>
是不同的类型,它们之间没有层次结构,也没有旁边广播.
For example, List<string>
and List<int>
are distinct types, there is no hierarchy between and no side-casting is available.
这篇关于C#:将具有派生接口的通用对象向下转换到基本接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!