[英]Generic Interface and Class / up casting is not working
我试图了解基本的继承和多态性概念。 但我陷入一种情况。
考虑以下代码:
接口:-
public interface IObject<T>
{
T Value { get; }
}
实施: -
public class MyObject<T> : IObject<T>
{
private T value;
public MyObject(T value)
{
this.value = value;
}
public T Value => value;
}
public class SquareObject : MyObject<Square>
{
public SquareObject(Square square) : base(square)
{
}
}
助手类和接口:
public interface IShape
{
}
public abstract class Shape : IShape
{
public abstract int Area();
}
public class Square : Shape
{
int length;
public Square(int len)
{
length = len;
}
public override int Area()
{
return length * length;
}
}
我的问题是,当我完成将方形物体铸造成形状时,它工作正常。
IShape shape = new Square(5);
但是,当我使用MyObject泛型类执行相同操作时,它不起作用。
var square = new Square(5);
IObject<IShape> gShape = new MyObject<Square>(square);
它说:“不能将类型MyObject<Square>
隐式转换为IObject<IShape>
”。 可能是的,我可以使用投射对其进行修复。 不铸造就可以吗?
同样,使用SquareObject
类也无法执行相同操作。
var square = new Square(5);
IObject<IShape> shapeObj = new SquareObject(square);
它说:“不能将类型SquareObject
隐式转换为IObject<IShape>
SquareObject
IObject<IShape>
”。 可能是的,我可以使用投射对其进行修复。 不铸造就可以吗?
您可以使用以下方法将IObject
接口声明为协变的
public interface IObject<out T>
{
T Value { get; }
}
协变意味着您可以将实现IObject<Derived>
的对象分配给IObject<Base>
类型的变量。 该文档可在此处找到。
如果没有显式指定协方差,则MyObject<Square>
是IObject<Square>
,但是不能将其分配给IObject<IShape>
类型的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.