开发者

c# inheritance & chaining question

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)?开发者_运维技巧?


The me method is returning a reference to the actual object, which is of the type Child, but the type of the reference is of the type Parent.

So, what you have is a reference of the type Parent that points to an object of the type Child. You can use that to access any members that the Child class inherits from the Parent class. To access the members of the Child class you have to cast the reference to the type Child:

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

You could make the me method return a Child reference and do the casting inside the method, but then it will of course not work to return a reference to a Parent object. If you don't use generics, each method can only have one return type. Even if you override the method in the Child class, it still has to return the same data type as in the Parent class.


Since you said no generics...

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

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

Also, as Darin said, it is the compile-time type that is off, not the actual object (instance) being returned.


No, (new Child()).me() returns a Child object, but the expression has type Parent.


No, new Child().me() is returning an instance of Child:

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

For compile-time safety you will need generics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜