c# – 如何强制转向泛型
作者:互联网
鉴于以下代码:
class Animal
{ }
class Dog : Animal
{ }
class Cage<T>
{
private T animal;
public Cage(T animal)
{
this.animal = animal;
}
public T Animal
{
get { return animal;}
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Cage<Animal> animalCage = new Cage<Animal>(dog);
Cage<Dog> dogCage = (Cage<Dog>)animalCage;
}
}
如何解决最后一个编译器错误(从animalCage转换为dogCage)?
在我的代码中我知道笼子里有一只狗,但是我找不到一种方法来施放它.是我创建转换器并创建新Cage< Dog>的独特替代方案.来自Cage< Animal>的价值的实例?
解决方法:
问题#1:你无法转动笼子< Animal>实例进入Cage< Dog>例如,你需要一个Cage< Dog>实例(或更具体类型的实例),其引用存储在较不特定类型的变量中.
更改
Cage<Animal> animalCage = new Cage<Animal>(dog);
Cage<Dog> dogCage = (Cage<Dog>)animalCage;
至
Cage<Animal> animalCage = new Cage<Dog>(dog);
Cage<Dog> dogCage = (Cage<Dog>)animalCage;
问题#2:您无法将引用存储到Cage< Dog> Cage< Animal>中的实例变量,因为类不支持共同/逆变.
更改
class Cage<T>
{
...
至
interface ICage<out T>
{
T Animal { get; }
}
class Cage<T> : ICage<T>
{
和
Cage<Animal> animalCage = new Cage<Dog>(dog);
Cage<Dog> dogCage = (Cage<Dog>)animalCage;
至
ICage<Animal> animalCage = new Cage<Dog>(dog);
ICage<Dog> dogCage = (Cage<Dog>)animalCage;
然后它工作. (如果您没有将新Cage< Animal>更改为新Cage< Dog>,则会在运行时获得强制转换异常.)
标签:c,generics,downcast 来源: https://codeday.me/bug/20190517/1124022.html