Loyiha uchun C # statik formasi qo'shilganmi?

Men dastur uchun maxsus xabar qutisini yaratmoqchiman, shuning uchun men deraza formasini qo'shdim. MessageBox kabi harakat qilishni istayman, chunki u statik va men faqatgina MessageBox.Show (a, b, c, ...) deyman. Shakllar dizaynerlarida, men buni qanday qilib statik qilishim mumkinligini bilmayman. Kodga faqat static qo'shsam bo'ladimi? Dizayner rejimida kamchiliklar mavjudmi?

Rahmat!

4

4 javoblar

MessageBox is not a static class, the Show method however is. Make Show static, in code. E.g.

public class MyMessageBox : Form
{
    public static int MyShow()
    {
       //create instance of your custom message box form
       //show it
       //return result 
    }
}
6
qo'shib qo'ydi
Buni MSDN dan ham ko'rishingiz mumkin. msdn.microsoft.com/en-us/library/ & hellip;
qo'shib qo'ydi muallif Austin Salonen, manba

Bu yangi uslubni ishlab chiqaradigan va harakatga keltiradigan statik usul bo'lib, muntazam sinfdir.

public class MyMessageBox
{
   public static MyResult Show(params)
   {
       var myMessageBox = new MyMessageBox();
       myMessageBox.Message = params ...
       return  myMessageBox.ShowDialog();
   }
}
4
qo'shib qo'ydi

O'zingiz ko'rsatadigan shaklga statik usul qo'shish va DialogResult-ni qaytaradi:

public partial class MyMessageBoxForm : Form {

  public static DialogResult Show(string message) {
    using (MyMessageBoxForm form = new MyMessageBoxForm(message)) {
      return form.ShowDialog();
    }

  private MyMessageBoxForm(string message) {
   //do something with message
  }

}
2
qo'shib qo'ydi

Ob'ektga murojaat qilmasdan unga kirish uchun statik Form1 yaratmoqchi bo'lsangiz, Program.cs ni o'zgartirishingiz mumkin:

public class Program
{
    public static Form1 YourForm; 

    [STAThread]
    static void Main(string[] args)
    {
        using (Form1 mainForm = new Form1())
        {
            YourForm = mainForm;
            Application.Run(mainForm);
        }
        YourForm = null;
    }
}

va dasturingizning har qanday joyidan Form1 sinf usullarini chaqiring:

Program.YouForm.DoAnything();

Boshqa mavzulardan foydalanish uchun "Invoke" deb chaqirishni unutmang.

1
qo'shib qo'ydi