C#将泛型子类型转换为父级 [英] C# Casting Generic Child Type to Parent
本文介绍了C#将泛型子类型转换为父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有以下几种类型:
Let's say we have these types:
class A {}
class B : A {}
class X<T> {}
为什么我们不能这样做?
Why we can't do this?
X<A> var = new X<B>();
有没有可用的解决方法?
Is there any workaround available?
我尝试使用协方差,但是失败了,因为我想访问X内部的T类型的属性,而C#不允许在接口中使用T类型:
I tried to use covariance but it failed because I want to access a property inside X that is of type T and C# does not allow using type T in the interface:
interface IX<out T> {
T sth {set; get;}
}
class X<T>: IX<T> {
T sth { set; get; }
}
我也尝试过,但是失败了:
I also tried this but it failed:
class X<T> where T : A
{
public T sth { set; get; }
public static implicit operator X<T>(X<B> v)
{
return new X<T>
{
sth = v.sth,
};
}
}
奇怪的是,C#不允许强制转换'sth'.
It's strange that C# does not allow to the casting for 'sth'.
推荐答案
问题是类不支持协方差和协方差,仅支持接口:
The problem is that classes does not support Covariance and Contravariance, only interfaces:
class A { }
class B : A { }
class X<T> : P<T> { }
interface P<out T>
{
}
...
P<A> var = new X<B>();
这篇关于C#将泛型子类型转换为父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文