VisualStudioを使わないでC#を書くのは非効率、変なことなのかもしれませんが、Windowsフォームアプリケーションを手書きで1から書くとしたら、次のどちらの書き方がよいでしょうか。もしくは、普通はもっと違う書き方をするものでしょうか。
■書き方 A
C#
1public class TestApp 2{ 3 public static void Main() 4 { 5 System.Windows.Forms.Form f = new System.Windows.Forms.Form(); 6 f.Width = 400; 7 f.Height = 300; 8 f.Text = "おみくじソフト"; 9 10 System.Windows.Forms.Label a = new System.Windows.Forms.Label(); 11 a.Width = 400; 12 a.Height = 100; 13 a.Text = "ボタンをクリックしてください"; 14 a.Name = "a"; 15 f.Controls.Add(a); 16 17 OmikujiButton b = new OmikujiButton(); 18 b.Text = "おみくじをひく"; 19 b.Location = new System.Drawing.Point(0, 150); 20 f.Controls.Add(b); 21 22 System.Windows.Forms.Application.Run(f); 23 } 24} 25 26public class OmikujiButton : System.Windows.Forms.Button 27{ 28 protected override void OnClick(System.EventArgs e) 29 { 30 System.Random rnd = new System.Random(); 31 int n = rnd.Next(0, 4); 32 33 System.String m; 34 if (n == 1) { 35 m = "大吉"; 36 } else if (n == 2) { 37 m = "小吉"; 38 } else if (n == 3) { 39 m = "吉"; 40 } else { 41 m = "凶"; 42 } 43 44 System.Windows.Forms.Form f = this.FindForm(); 45 System.Windows.Forms.Control a = f.Controls.Find("a", false)[0]; 46 a.Text = "今日の運勢は " + m; 47 } 48}
■書き方 B
C#
1public class TestApp 2{ 3 static System.Windows.Forms.Form f; 4 static System.Windows.Forms.Label a; 5 static System.Windows.Forms.Button b; 6 7 public static void Main() 8 { 9 f = new System.Windows.Forms.Form(); 10 f.Width = 400; 11 f.Height = 300; 12 f.Text = "おみくじソフト"; 13 14 a = new System.Windows.Forms.Label(); 15 a.Width = 400; 16 a.Height = 100; 17 a.Text = "ボタンをクリックしてください"; 18 a.Name = "a"; 19 f.Controls.Add(a); 20 21 b = new System.Windows.Forms.Button(); 22 b.Click += new System.EventHandler(TestApp.b_Click); 23 b.Text = "おみくじをひく"; 24 b.Location = new System.Drawing.Point(0, 150); 25 f.Controls.Add(b); 26 27 System.Windows.Forms.Application.Run(f); 28 } 29 30 public static void b_Click(object sender, System.EventArgs e) 31 { 32 System.Random rnd = new System.Random(); 33 int n = rnd.Next(0, 4); 34 35 System.String m; 36 if (n == 1) { 37 m = "大吉"; 38 } else if (n == 2) { 39 m = "小吉"; 40 } else if (n == 3) { 41 m = "吉"; 42 } else { 43 m = "凶"; 44 } 45 46 a.Text = "今日の運勢は " + m; 47 } 48}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/09/01 14:39
2015/09/01 23:46