我想将泛型类转换为其基本类型,并具有该类和类型继承。
我有这些课程:
public class Segment<K> : SomeStructure where K : SomeStructure{...}
public class XXXXXXData : Segment<Key> {...}
public class Key : SomeStructure {...}
我有一个名为XXXXXXData
的{{1}}实例,但是如果我像
data
返回data as Segment<SomeStructure>
。
在我有这些代码的地方,变量可以是null
或任何类型的XXXXData
。我该怎么做才能转换为Segment<>
,以便可以使用这些基类的方法?
答案 0 :(得分:1)
您无法在C#中做到这一点。您只能通过在顶层引入通用接口来做到这一点,该通用接口使用127.0.0.1
对通用参数进行协变,例如:
out
您的界面应如下所示:
public class Segment<K> : ISegment<K> where K : SomeStructure{...}
,您的转换代码现在将使用接口类型:
public interface ISegment<out T>
{
}