回答編集履歴

1

追記

2018/12/08 12:48

投稿

退会済みユーザー
test CHANGED
@@ -1 +1,155 @@
1
1
  msdn ライブラリを見てください、ひとつのクラスのコンストラクターにも多数のオーバーロードがあるのが分かります。当然需要があるからです。
2
+
3
+
4
+
5
+ 【追伸】
6
+
7
+
8
+
9
+ 具体例を示した方がよさそうですので、SQL Server にアクセスするときに使う SqlConnection, SqlCommand, SqlParameter クラスのコンストラクタで、引数有りと引数無しの場合のサンプルを書いておきます。
10
+
11
+
12
+
13
+ どちらがスマート&可読性が高いかと言えば前者ではないでしょうか?
14
+
15
+
16
+
17
+
18
+
19
+ ```
20
+
21
+ using System;
22
+
23
+ using System.Collections.Generic;
24
+
25
+ using System.Linq;
26
+
27
+ using System.Text;
28
+
29
+ using System.Threading.Tasks;
30
+
31
+ using System.Data;
32
+
33
+ using System.Data.SqlClient;
34
+
35
+
36
+
37
+ namespace ConsoleApplication2
38
+
39
+ {
40
+
41
+ class Program
42
+
43
+ {
44
+
45
+ static void Main(string[] args)
46
+
47
+ {
48
+
49
+ string connString = @"Data Source=(local)\sqlexpress;Initial Catalog=NORTHWIND;Integrated Security=True";
50
+
51
+ string query = "SELECT [ProductID], [ProductName] FROM [Products] WHERE [CategoryID]=@ID";
52
+
53
+
54
+
55
+ // コンストラクタ引数有り
56
+
57
+ using (SqlConnection connection = new SqlConnection(connString))
58
+
59
+ {
60
+
61
+ using (SqlCommand command = new SqlCommand(query, connection))
62
+
63
+ {
64
+
65
+ command.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int));
66
+
67
+
68
+
69
+ // これ以下は同じ
70
+
71
+ command.Parameters["@ID"].Value = 1;
72
+
73
+ connection.Open();
74
+
75
+ using (SqlDataReader reader = command.ExecuteReader())
76
+
77
+ {
78
+
79
+ while (reader.Read())
80
+
81
+ {
82
+
83
+ Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}");
84
+
85
+ }
86
+
87
+ }
88
+
89
+ }
90
+
91
+ }
92
+
93
+
94
+
95
+ // コンストラクタ引数無し
96
+
97
+ using (SqlConnection connection = new SqlConnection())
98
+
99
+ {
100
+
101
+ connection.ConnectionString = connString;
102
+
103
+ using (SqlCommand command = new SqlCommand())
104
+
105
+ {
106
+
107
+ command.CommandText = query;
108
+
109
+ command.Connection = connection;
110
+
111
+ SqlParameter param = new SqlParameter();
112
+
113
+ param.ParameterName = "@ID";
114
+
115
+ param.SqlDbType = SqlDbType.Int;
116
+
117
+ command.Parameters.Add(param);
118
+
119
+
120
+
121
+ // これ以下は同じ
122
+
123
+ command.Parameters["@ID"].Value = 1;
124
+
125
+ connection.Open();
126
+
127
+ using (SqlDataReader reader = command.ExecuteReader())
128
+
129
+ {
130
+
131
+ while (reader.Read())
132
+
133
+ {
134
+
135
+ Console.WriteLine($"ID: {reader.GetInt32(0)}, Name: {reader.GetString(1)}");
136
+
137
+ }
138
+
139
+ }
140
+
141
+ }
142
+
143
+ }
144
+
145
+ }
146
+
147
+ }
148
+
149
+ }
150
+
151
+ ```
152
+
153
+
154
+
155
+ その他、例えば(あくまで例えばですが)、Windows Forms アプリで Form1 で初期化してDB からデータを Fill した DataTable オブジェクトへの参照を Form2 に渡す場合など、Form2(DataTable table) というコンストラクタを定義して、Form2 を初期化するときに渡すということも可能です。