1
public class Parent
{
    public virtual Parent me()
    {
        return this;
    }
}

public class Child : Parent
{
}

new Child().me() 正在返回一个 Parent 对象。我需要什么让它返回子对象本身(不使用扩展名和泛型)?

4

4 回答 4

6

me方法返回对实际对象的引用,该对象属于 type Child,但引用的类型属于 type Parent

因此,您所拥有的是Parent指向 type 对象的类型的引用ChildChild您可以使用它来访问该类从该类继承的任何成员Parent。要访问类的成员,Child您必须将引用转换为 type Child

Child c = (Child)someObject.me();

您可以让me方法返回一个Child引用并在方法内部进行强制转换,但是返回对对象的引用当然是行不通的Parent。如果不使用泛型,每个方法只能有一个返回类型。即使你重写了Child类中的方法,它仍然必须返回与类中相同的数据类型Parent

于 2010-06-29T17:01:58.277 回答
2

既然你说没有泛型...

public class Parent
{
    public virtual Parent me()
    {
        return this;
    }
}

public class Child : Parent
{
    new public Child me ()
    {
        return this;
    }
}

此外,正如 Darin 所说,关闭的是编译时类型,而不是返回的实际对象(实例)。

于 2010-06-29T17:00:45.317 回答
1

不,(new Child()).me()返回一个Child对象,但表达式type Parent

于 2010-06-29T17:01:09.637 回答
0

不,new Child().me()正在返回一个实例Child

Console.WriteLine(new Child().me()); // prints Child

为了编译时安全,您将需要泛型。

于 2010-06-29T16:58:54.710 回答