2011-05-06 56 views
5

我有一个父类有一个重载的构造函数,并且我有一个具有可选参数的构造函数的子类。有没有办法让子类的构造函数仍然暴露父类的重载性,同时保留它自己的可选参数?在C#4中,如何在具有重载构造函数的父类的子类中使用可选参数构造函数?

下面是两个阶级,他们需要的构造函数的一些示例代码:

class Foo { 
    Foo(String arg0) 
    { 
     // do some stuff with arg0 
    } 

    Foo(String arg0, List<x> arg1) 
     : this(arg0) 
    { 
     // do some other stuff with arg1 that is special because we have an arg1 
    } 
} 

class Bar : Foo { 
    Bar(String arg0, List<y> arg2 = null, String arg3 = "") 
     : base(arg0) 
    { 
     // some third thing with arg2 and arg3 
    } 
} 

这对于其他子类的构造,我想也有揭露父构造函数的重载方法签名,但问题是如何做到这一点:

Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "") 

我有,我想,找到了解决办法,但我不知道它是干净的,因为它可以。我已将其作为答案发布,以防万一它是唯一的选择。

+0

你能不能改Foo'的'签名只是有一个构造函数'美孚(字符串为arg0,列表 arg1 = null)'?或者你需要区分传递null还是不传递一个值? – Davy8 2011-05-06 19:06:53

+0

@ Davy8 - 我需要区分传递null与不传递任何参数。我会更新这个例子来反映这一点。不幸的是,这个例子比这个例子复杂得多,但我在这里是关键。 – cdeszaq 2011-05-06 19:10:24

+1

我个人试图重新审视设计,看看是否有可能将其改为没有这个要求,但很难说如果不知道更多关于它应该做什么的可能性。 – Davy8 2011-05-06 19:13:22

回答

1

这里是解决方案,我想出了:

class Foo { 
    Foo(String arg0) 
    { 
     // do some stuff with arg0 
    } 

    Foo(String arg0, List<x> arg1) 
     : this(arg0) 
    { 
     // do some other stuff with arg1 
    } 
} 

class Bar : Foo { 
    Bar(String arg0, List<y> arg2 = null, String arg3 = "") 
     : base(arg0) 
    { 
     this.Initialize(arg2, arg3); 
    } 

    Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "") 
     : base(arg0, arg1) 
    { 
     this.Initialize(arg2, arg3); 
    } 

    private void Initialize(List<y> arg2, String arg3) 
    { 
     // some third thing with arg2 and arg3 
    } 
} 

这似乎有点不干净,因为我不是链接的子类的构造函数一起和我调用一个函数,而不是,但我想不出任何其他方式来做到这一点。

3

如果你可以改变Foo到只有一个构造函数带有可选参数,你可以做到以下几点:

public class Foo 
{ 
    public Foo(String arg0, List<x> arg1 = null) 
    { 
     // do some stuff with arg0 
     if (arg1 != null) 
     { 
      // do some other stuff with arg1 
     } 
    } 
} 

public class Bar : Foo 
{ 
    public Bar(String arg0, List<x> arg1 = null, List<y> arg2 = null, String arg3 = "") 
     : base(arg0, arg1) 
    { 
     // some third thing with arg2 and arg3 
    } 
} 
相关问题