类有两个构造函数

class have two constructors

提问人:sam it 提问时间:7/12/2018 最后编辑:NoviceProgrammersam it 更新时间:7/12/2018 访问量:213

问:

我的类有两个构造函数

class test()

    // declare
    par1 as object, par2 as  object , par3 as object

    // constructors
    public test(par1, par2) {,,,,}
    public test(par1, par2, par3) {,,,,,}

    // Methods 
     fct1() 
     {
          '' do something with par1 and par2
     }


     fct2(){

           if(par3 is null) 
             throw exception ('be sure to use the right constructor ) 
           else
           '' do something with par1 and par2
             and par3
     }

我的问题:

有两个这样的构造函数可以吗:

因为如果有人需要使用 FCT2,他应该 使用构造函数编号 2(具有 3 个参数) 否则它将抛出异常

可以还是有其他更好的解决方案

PS:如果我更改第一个构造函数,则每个位置都会实现此类 我需要更改调用类的每个位置

谢谢。

C# .net

评论

7赞 CodeCaster 7/12/2018
这看起来并不像 C#。
1赞 Damien_The_Unbeliever 7/12/2018
可能有更好的方法(例如,带有两个 parms + fct1 的基类和一个带有额外参数和 fct2 的子类),但很难说你什么时候把问题说得太抽象了,以至于我们不知道你到底在做什么。
2赞 Paul Karam 7/12/2018
没关系,也不行。这完全取决于你想要什么行为。
0赞 sam it 7/12/2018
这只是示例,但我使用 C# 进行编码
0赞 MakePeaceGreatAgain 7/12/2018
从语法上讲,它很好,构造函数 - 就像每个方法一样 - 可以被任意参数重载。如果这是你真正想要的,那是另一个问题。

答:

2赞 CodeCaster 7/12/2018 #1

因此,您有一个包含两个方法的类,第二个方法将功能添加到第一个方法中。听起来像是继承的理想人选:

public class FirstImplementation
{
    public FirstImplementation(param1, param2)
    {
    }

    public virtual Bar Foo()
    {
        // do something with param1, param2
    }
}

然后继承它以调整其行为:

public class SecondImplementation : FirstImplementation
{
    public SecondImplementation(param1, param2, param3)
        : base(param1, param2)
    {
    }

    public override Bar Foo()
    {
        // do something with param1, param2 and param3, perhaps by calling base.Foo().
    }
}

因为您不希望类包含两次相同的代码并稍作更改,因此这要求调用方在调用其方法之一之前知道要调用哪个构造函数,或者在调用错误的构造函数时引发 InvalidOperationException。这是不可用和不可维护的。