减少继承的构造函数的参数列表的类型开销

时间:2018-04-18 14:51:06

标签: c# constructor copy-constructor

是否有任何语法和/或语言功能可以减少在继承的构造函数中重新输入参数列表的开销?

基类

public class Cartesian
{
    public int X { get; set; }
    public int Y { get; set; }

    public Cartesian(int x, int y)
    {
        X = x;
        Y = y;
    }
}

继承类

public class Complex : Cartesian
{
    public int I { get; set; }

    // all this retyping becomes daunting and results in duplicate code
    public Complex(int x, int y, int i) : base(x, y)
    {
        I = i;
    }
}

3 个答案:

答案 0 :(得分:2)

如果您拥有ReSharper 8,则会有一项名为Generative Completion的功能。

  

在ReSharper 8中出现的一种代码完成形式是   称为生成完成。生成完成的想法是   使用代码完成代码生成更快,更直接   替代,例如,生成菜单。

换句话说,键入ctorp并按Tab键生成ctor

public class Complex : Cartesian
{
    public int I { get; set; }

    ctorp//tab key
}

产生

public Complex(int x, int y) : base(x, y)
{
     I = x;
}

您仍然必须填写派生类成员并执行分配,但它可以减少开销。

答案 1 :(得分:0)

这是一种某种解决方法,但它只是将重复的代码移动到Init函数中,所以......:

基类

public class Cartesian
{
    public int X { get; set; }
    public int Y { get; set; }

    //public Cartesian(int x, int y) { Init(x, y); }

    public void Init(int x, int y)
    {
        X = x;
        Y = y;        
    }
}

继承类

public class Complex : Cartesian
{
    public Cartesian Base { get {return base;} }

    public int I { get; set; }

    //public Complex(int i) { Init(i); }

    public Complex Init(int i)
    {
        I = i;

        return this;
    }
}

使用示例

var complex = (new Complex()).Init(i).Base.Init(x, y);

答案 2 :(得分:0)

P.Brian.Mackey 回答,如果 ctorp 被替换为关键字,请说 base.ctorp:

public class Complex : Cartesian
{
    public int I { get; set; }

    //public Complex(int x, int y, int i) : base(x, y)
    public Complex(int i) : base.ctorp
    {
        I = i;
    }
}

然后让编译器根据签名确定调用哪个构造函数并相应地替换 ctorp (并且可能有一些解释符号来补充):

var Complex = new Complex((x, y), i);

产生

    //public Complex(int i) : base.ctorp
    public Complex(int x, int y, int i) : base(x, y)
    {
        I = i;
    }

var Complex = new Complex(i);

产生

    //public Complex(int i) : base.ctorp
    public Complex(int i) : base()
    {
        I = i;
    }