簡體   English   中英

類有兩個構造函數

[英]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:如果我更改了第一個構造函數,則在每個地方實現該類,我需要在每個地方更改該類的位置

謝謝 。

因此,您有一個帶有兩個方法的類,第二個方法為第一個方法添加了功能。 聽起來像是繼承的理想人選:

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。 那是無法使用和維持的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM