teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記

2018/12/08 12:48

投稿

退会済みユーザー
answer CHANGED
@@ -1,1 +1,78 @@
1
- msdn ライブラリを見てください、ひとつのクラスのコンストラクターにも多数のオーバーロードがあるのが分かります。当然需要があるからです。
1
+ msdn ライブラリを見てください、ひとつのクラスのコンストラクターにも多数のオーバーロードがあるのが分かります。当然需要があるからです。
2
+
3
+ 【追伸】
4
+
5
+ 具体例を示した方がよさそうですので、SQL Server にアクセスするときに使う SqlConnection, SqlCommand, SqlParameter クラスのコンストラクタで、引数有りと引数無しの場合のサンプルを書いておきます。
6
+
7
+ どちらがスマート&可読性が高いかと言えば前者ではないでしょうか?
8
+
9
+
10
+ ```
11
+ using System;
12
+ using System.Collections.Generic;
13
+ using System.Linq;
14
+ using System.Text;
15
+ using System.Threading.Tasks;
16
+ using System.Data;
17
+ using System.Data.SqlClient;
18
+
19
+ namespace ConsoleApplication2
20
+ {
21
+ class Program
22
+ {
23
+ static void Main(string[] args)
24
+ {
25
+ string connString = @"Data Source=(local)\sqlexpress;Initial Catalog=NORTHWIND;Integrated Security=True";
26
+ string query = "SELECT [ProductID], [ProductName] FROM [Products] WHERE [CategoryID]=@ID";
27
+
28
+ // コンストラクタ引数有り
29
+ using (SqlConnection connection = new SqlConnection(connString))
30
+ {
31
+ using (SqlCommand command = new SqlCommand(query, connection))
32
+ {
33
+ command.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int));
34
+
35
+ // これ以下は同じ
36
+ command.Parameters["@ID"].Value = 1;
37
+ connection.Open();
38
+ using (SqlDataReader reader = command.ExecuteReader())
39
+ {
40
+ while (reader.Read())
41
+ {
42
+ Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}");
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ // コンストラクタ引数無し
49
+ using (SqlConnection connection = new SqlConnection())
50
+ {
51
+ connection.ConnectionString = connString;
52
+ using (SqlCommand command = new SqlCommand())
53
+ {
54
+ command.CommandText = query;
55
+ command.Connection = connection;
56
+ SqlParameter param = new SqlParameter();
57
+ param.ParameterName = "@ID";
58
+ param.SqlDbType = SqlDbType.Int;
59
+ command.Parameters.Add(param);
60
+
61
+ // これ以下は同じ
62
+ command.Parameters["@ID"].Value = 1;
63
+ connection.Open();
64
+ using (SqlDataReader reader = command.ExecuteReader())
65
+ {
66
+ while (reader.Read())
67
+ {
68
+ Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}");
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ その他、例えば(あくまで例えばですが)、Windows Forms アプリで Form1 で初期化してDB からデータを Fill した DataTable オブジェクトへの参照を Form2 に渡す場合など、Form2(DataTable table) というコンストラクタを定義して、Form2 を初期化するときに渡すということも可能です。