我应该如何在类层次结构中链接构造函数? [英] How should I chain the constructors in a class hierarchy?

查看:83
本文介绍了我应该如何在类层次结构中链接构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们具有以下类层次结构:

We have the following class hierarchy:

public class Base
{
    public Base()
    {
        // do generic initialization 
    }

    public Base(SomeClass param1) : this()
    {
        // init properties that require param1
    }

    public Base(SomeClass param1, OtherClass param2) : this(param1)
    {
        // init properties that require param2
    }

    // ...
}

public class Derived : Base
{
    public Derived()
    {
        // do custom initialization 
    }

    public Derived(SomeClass param1) : this() // ???
    {
        // do custom initialization using param1
    }

    public Derived(SomeClass param1, OtherClass param2) : this(param1) // ???
    {
        // do custom initialization using param2
    }

    // ...
}

我们需要 Derived 来运行两者自己的初始化例程,链,以及来自基类的对应链。我们如何链接构造函数而不重复代码/不运行某些构造函数两次?

We would require Derived to run both its own initialization routines, up the chain, and the corresponding ones from the base class. How do we chain the constructors without duplicating code/running some of the constructors twice?

推荐答案

在派生类链中,构造函数具有最少的参数传递给具有最多参数的构造函数,然后将派生的具有最多参数的构造函数链接到基数。像这样的东西:

In the derived class chain the constructors with the least parameters to the constructor with the most parameters, and then the derived constructor with the most parameters is chained to base. Something like this:

public class Base 
{
  public Base() : this(null, null)
  {
  }
  public Base(SomeClass param1) : this(param1, null)
  {
  }
  public Base(SomeClass param1, OtherClass param2)
  {
    if (param1 != null)
    {
      // initialise param1
    }
    if (param2 != null)
    {
      // initialise param2
    }
  }
}

public class Derived : Base
{
  public Derived() : this(null, null)
  {
  }
  public Derived(SomeClass param1) : this(param1, null)
  {
  }
  public Derived(SomeClass param1, OtherClass param2) : base(param1, param2)
  {
  }
} 

根据上下文,最好使用default(T)而不是null来表示丢失/默认值。

Depending on the context, it may be better to use default(T) instead of null to indicate a missing/default value.

这篇关于我应该如何在类层次结构中链接构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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