时间:2019-03-17 标签:c#inheritance&连锁问题
public class Parent
{
public virtual Parent me()
{
return this;
}
}
public class Child : Parent
{
}
new Child().me() 返回一个 Parent 对象。我需要什么才能让它返回子对象本身(不使用扩展和泛型)?
public class Parent
{
public virtual Parent me()
{
return this;
}
}
public class Child : Parent
{
}
new Child().me() is returning a Parent object. What do i need to have it return the Child object itself (without using extension and generic)??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
me
方法返回对实际对象的引用,该对象的类型为Child
,但引用的类型为Parent
类型>。因此,您拥有的是
Parent
类型的引用,它指向Child
类型的对象。您可以使用它来访问Child
类从Parent
类继承的任何成员。要访问Child
类的成员,您必须将引用强制转换为Child
类型:您可以使
me
方法返回一个Child
引用并在方法内进行转换,但是返回对Parent
对象的引用当然不起作用。如果不使用泛型,则每个方法只能有一种返回类型。即使您重写Child
类中的方法,它仍然必须返回与Parent
类中相同的数据类型。The
me
method is returning a reference to the actual object, which is of the typeChild
, but the type of the reference is of the typeParent
.So, what you have is a reference of the type
Parent
that points to an object of the typeChild
. You can use that to access any members that theChild
class inherits from theParent
class. To access the members of theChild
class you have to cast the reference to the typeChild
:You could make the
me
method return aChild
reference and do the casting inside the method, but then it will of course not work to return a reference to aParent
object. If you don't use generics, each method can only have one return type. Even if you override the method in theChild
class, it still has to return the same data type as in theParent
class.既然你说没有泛型......
另外,正如达林所说,关闭的是编译时类型,而不是返回的实际对象(实例)。
Since you said no generics...
Also, as Darin said, it is the compile-time type that is off, not the actual object (instance) being returned.
否,
(new Child()).me()
返回一个Child
对象,但表达式具有类型父级
。No,
(new Child()).me()
returns aChild
object, but the expression has typeParent
.不,
new Child().me()
返回Child
的实例:为了编译时安全,您将需要泛型。
No,
new Child().me()
is returning an instance ofChild
:For compile-time safety you will need generics.