[英]Getting generic type from the DeclaringType of a nested type in C# with reflection
[英]C# : Create a Tuple from a generic type using reflection
我希望能夠將元組傳遞給以下方法,但是由於必須實例化它,因此無法這樣做。
public List<T> Select<T>(string sql, DbCommand command) where T : new()
{
DbDataReader dataReader = null;
List<T> ls = new List<T>();
Type tType = typeof(T);
T t;
PropertyInfo prop = null;
string[] propertiesNames = GetPropertiesNamesFromSQL(sql);
try
{
dataReader = command.ExecuteReader();
if (dataReader == null || !dataReader.HasRows) return ls;
while (dataReader.Read())
{
t = new T();
for (int i = 0; i < dataReader.FieldCount; i++)
{
prop = tType.GetProperty(propertiesNames[i]);
prop.SetValue(t, dataReader.GetValue(i));
}
ls.Add(t);
}
}
catch (Exception){ }
finally
{
if (dataReader != null) dataReader.Close();
}
return ls;
}
正如我在評論中說的那樣,我正在嘗試構建裸露的ORM,我只對映射到對象部分感興趣。 它按原樣工作,但是有時快速查詢能夠傳遞元組而不是完整的類有時是實用的。
有什么解決辦法嗎?
這種方式行不通。 由於許多原因,創建一種可以從數據庫生成任何東西的方法並不是一個好的解決方案。
正確的方法要復雜一些。 我認為您需要一個工廠接口,如下所示:
public interface IMyFactory<T> where T : new()
{
T Create ( string name );
}
然后是一個混凝土工廠:
public class MyFactory : IMyFactory<MyClient>
{
public MyClient Create ( string name )
{
var t = new MyClient();
t.ClientName = name;
return t;
}
}
然后將其傳遞給您的方法,例如:
public List<T> SelectFromDataBase<T> ( IMyFactory<T> factory ) where T : new()
{
var ls = new List<T>();
// highly simplified here
T t = factory.Create("Mr Smith");
ls.Add(t);
return ls;
}
然后可以將您的方法調用為:
var myList = SelectFromDataBase(new MyFactory());
這樣,您就可以將數據從數據庫轉換為與對象創建邏輯分離的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.