[英]Generic Interface and Class / up casting is not working
I'm trying to understand basic Inheritance and polymorphism concepts. 我试图了解基本的继承和多态性概念。 but I'm stuck in one scenario.
但我陷入一种情况。
Consider the following code: 考虑以下代码:
Interface:- 接口:-
public interface IObject<T>
{
T Value { get; }
}
Implementation:- 实施: -
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 Classes And Interface:- 助手类和接口:
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;
}
}
My question is when I do up casting of square object to shape, it's working fine. 我的问题是,当我完成将方形物体铸造成形状时,它工作正常。
IShape shape = new Square(5);
But when I do the same using MyObject generic class, it doesn't work. 但是,当我使用MyObject泛型类执行相同操作时,它不起作用。
var square = new Square(5);
IObject<IShape> gShape = new MyObject<Square>(square);
It says "Cannot implicitly convert type MyObject<Square>
to IObject<IShape>
". 它说:“不能将类型
MyObject<Square>
隐式转换为IObject<IShape>
”。 May be, I can fix it using casting. 可能是的,我可以使用投射对其进行修复。 Can it be possible without casting?
不铸造就可以吗?
Similarly, I'm also not able to do the same using SquareObject
class. 同样,使用
SquareObject
类也无法执行相同操作。
var square = new Square(5);
IObject<IShape> shapeObj = new SquareObject(square);
It says "Cannot implicitly convert type SquareObject
to IObject<IShape>
". 它说:“不能将类型
SquareObject
隐式转换为IObject<IShape>
SquareObject
IObject<IShape>
”。 May be, I can fix it using casting. 可能是的,我可以使用投射对其进行修复。 Can it be possible without casting?
不铸造就可以吗?
You could declare your IObject
interface as covariant using 您可以使用以下方法将
IObject
接口声明为协变的
public interface IObject<out T>
{
T Value { get; }
}
Covariant means that you can assign an object implementing IObject<Derived>
to a variable of type IObject<Base>
. 协变意味着您可以将实现
IObject<Derived>
的对象分配给IObject<Base>
类型的变量。 The documentation can be found here . 该文档可在此处找到。
Without explicitly specifying covariance your MyObject<Square>
is an IObject<Square>
, but it can't be assigned to a variable of type IObject<IShape>
. 如果没有显式指定协方差,则
MyObject<Square>
是IObject<Square>
,但是不能将其分配给IObject<IShape>
类型的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.