最后从同一个类中的其他构造函数调用构造函数

pro*_*ice 1 c#

我在这里读到可以调用另一个构造函数从同一个类中的其他构造函数调用构造函数

但它在开始时调用另一个构造函数,而我想在最后调用.这可能吗 ?

要求具体的人的更新:在program.cs中,我希望能够做到,具体取决于某些情况

这个:

// Form1 will show a message from its own private member
Application.Run(new Form1());
Run Code Online (Sandbox Code Playgroud)

或这个:

// Form1 will show a message from class1 member (kind of overloading form1 message if class1 exists)
Application.Run(new Form1(new Class1()));
Run Code Online (Sandbox Code Playgroud)

我有Form1

private string member = "Test Sample if no class1";
Run Code Online (Sandbox Code Playgroud)

在class1我有

private string member = "Test Sample from class1";
public string member;
{
    get { return this.member; }
    set { this.member = value; }
}
Run Code Online (Sandbox Code Playgroud)

在Form1中,我有这两个构造函数

// of course Form1() could contain 100 lines of code
Form1() { MessageBox.Show(this.member); }

// I don't want to duplicate 100 lines in second constructor
// so I need to call first constructor
Form1(class1) {
    this.member = class1.member;
    // this is where I would now like to call Form1()
    // but the syntax below doesn't work
    this();
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*örk 12

不是我知道的.您可能应该将最后需要执行的初始化代码移动到一个单独的私有方法中,并在适当的情况下从两个构造函数调用它.

  • 当然是啦.`Form1(){init(); Form1(Class1 class1){this.member = class1.member; 在里面(); } private void init(){MessageBox.Show(this.member); }` (3认同)

小智 7

不,如果使用构造函数链接,则始终首先调用基类构造函数.


Hen*_*man 7

不,构造函数机制非常清晰和严格,您只能在编写之前"调用"其他构造函数.

但是你可以利用这个优势,只需改变你的想法(方法),使'last'构造函数成为用户调用的构造函数.要弄清楚具体细节,您必须发布一些示例代码.

编辑:

有一些简单的解决方法,例如:

class Form1
{
   public Form1(Class1 c1)
   {
      if (c1 != null) this.member = c1.member;
   }

   public Form1() : this(null)
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

但是你不允许在另一个内部调用构造函数形式,这会产生更多问题.