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() 正在返回一个 Parent 对象。我需要什么让它返回子对象本身(不使用扩展名和泛型)?
该me
方法返回对实际对象的引用,该对象属于 type Child
,但引用的类型属于 type Parent
。
因此,您所拥有的是Parent
指向 type 对象的类型的引用Child
。Child
您可以使用它来访问该类从该类继承的任何成员Parent
。要访问类的成员,Child
您必须将引用转换为 type Child
:
Child c = (Child)someObject.me();
您可以让me
方法返回一个Child
引用并在方法内部进行强制转换,但是返回对对象的引用当然是行不通的Parent
。如果不使用泛型,每个方法只能有一个返回类型。即使你重写了Child
类中的方法,它仍然必须返回与类中相同的数据类型Parent
。
既然你说没有泛型...
public class Parent
{
public virtual Parent me()
{
return this;
}
}
public class Child : Parent
{
new public Child me ()
{
return this;
}
}
此外,正如 Darin 所说,关闭的是编译时类型,而不是返回的实际对象(实例)。
不,(new Child()).me()
返回一个Child
对象,但表达式有type Parent
。
不,new Child().me()
正在返回一个实例Child
:
Console.WriteLine(new Child().me()); // prints Child
为了编译时安全,您将需要泛型。