提问人:sam it 提问时间:7/12/2018 最后编辑:NoviceProgrammersam it 更新时间:7/12/2018 访问量:213
类有两个构造函数
class have two constructors
问:
我的类有两个构造函数
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:如果我更改第一个构造函数,则每个位置都会实现此类 我需要更改调用类的每个位置
谢谢。
答:
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。这是不可用和不可维护的。
评论