【问题标题】:c# inheritance & chaining questionc#继承和链接问题
【发布时间】:2010-06-29 16:56:20
【问题描述】:
public class Parent
{
    public virtual Parent me()
    {
        return this;
    }
}

public class Child : Parent
{
}

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

【问题讨论】:

    标签: c# inheritance chaining


    【解决方案1】:

    me 方法返回一个对实际对象的引用,它的类型是 Child,但引用的类型是 Parent

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

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

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

    【讨论】:

      【解决方案2】:

      既然你说没有泛型...

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          不,new Child().me() 正在返回 Child 的实例:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-17
            • 2012-05-11
            • 2011-09-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多