基类中的方法可以以某种方式返回子类吗? [英] Can somehow a method from base class return child class?

查看:48
本文介绍了基类中的方法可以以某种方式返回子类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将举一个例子,以便您可以更好地理解我的意思:

I'll give an example, so you can better understand what i mean:

public class Base
{
      public Base Common()
      {
          return this;
      }
}

public class XBase : Base
{

     public XBase XMethod()
     {
          return this;
     }
}

我希望能够做类似的事情:

I want to be able to do something like:

var a = new XBase().Common().XMethod();

但这是不可能的,因为 Common()返回 Base ,并且 XMethod()未在 Base 中定义代码>.

but this is not possible as Common() returns Base, and XMethod() is not defined in Base.

我有什么办法可以完成这个任务吗?

Is there any possible way i could acomplish this ?

我问是因为我有一个 BaseComponent ,以及许多其他继承该类的 Components ,而且我必须在每个方法中声明通用方法,只是在内部调用 base.Method().

I'm asking because i have a BaseComponent, and a lot of other Components that inherit this class, and i have to declare the common methods in each one, just to call base.Method() inside.

感谢您的帮助.

PS:不使用泛型并指定孩子的类型:

PS: without using generics and specifying the child's type:

var a = new XBase().Common<XBase>().XMethod();

推荐答案

您可以使 Base 通用并使用然后您可以使用:

var a = new XBase().Common().XMethod();

这篇关于基类中的方法可以以某种方式返回子类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆