【发布时间】:2018-05-26 06:04:15
【问题描述】:
我正在尝试理解基本的继承和多态性概念。但我陷入了一种情况。
考虑以下代码:
界面:-
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)
{
}
}
Helper 类和接口:-
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>”。可能是,我可以使用强制转换来修复它。不铸造也可以吗?
【问题讨论】:
标签: c# inheritance polymorphism