C#에서 제네릭을 사용하기 시작했습니다. 예를 들어 내가 한 것은 일반적인 메소드를 구현하는 추상 클래스가 있다는 것입니다. 이러한 일반 메서드는 SQL 쿼리, 연결 문자열 및 Type T를 매개 변수로 취한 다음 데이터 집합을 구성하고 개체를 채우고 다시 반환합니다. 이렇게하면 각 Business Object에는 데이터를 채우거나 데이터 세트를 작성하는 메소드가있을 필요가 없습니다. 우리가해야 할 일은 타입, SQL 질의, 연결 문자열을 전달하는 것입니다. 나머지는이 메소드가 수행합니다. 코드 샘플을 여기에 제공하고 있습니다. 나는 내가 한 일에 대해 더 나은 해결책을 가지고있는 사람들과 토론하기를 기대하고있다.C#의 제네릭 사용
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using MWTWorkUnitMgmtLib.Business; using System.Collections.ObjectModel; using System.Reflection; namespace MWTWorkUnitMgmtLib.TableGateway { public abstract class TableGateway { public TableGateway() { } protected abstract string GetConnection(); protected abstract string GetTableName(); public DataSet GetDataSetFromSql(string connectionString, string sql) { DataSet ds = null; using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandText = sql; connection.Open(); using (ds = new DataSet()) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { adapter.Fill(ds); } } return ds; } public static bool ContainsColumnName(DataRow dr, string columnName) { return dr.Table.Columns.Contains(columnName); } public DataTable GetDataTable(string connString, string sql) { DataSet ds = GetDataSetFromSql(connString, sql); DataTable dt = null; if (ds != null) { if (ds.Tables.Count > 0) { dt = ds.Tables[0]; } } return dt; } public T Construct(DataRow dr, T t) where T : class, new() { Type t1 = t.GetType(); PropertyInfo[] properties = t1.GetProperties(); foreach (PropertyInfo property in properties) { if (ContainsColumnName(dr, property.Name) && (dr[property.Name] != null)) property.SetValue(t, dr[property.Name], null); } return t; } public T GetByID(string connString, string sql, T t) where T : class, new() { DataTable dt = GetDataTable(connString, sql); DataRow dr = dt.Rows[0]; return Construct(dr, t); } public List GetAll(string connString, string sql, T t) where T : class, new() { List collection = new List(); DataTable dt = GetDataTable(connString, sql); foreach (DataRow dr in dt.Rows) collection.Add(Construct(dr, t)); return collection; } } }
나는 이것이 StackOverflow.com에 대한 질문이라고 생각한다. – Guillaume86