[英]C# : Create a Tuple from a generic type using reflection
I would like to be able to pass a Tuple to the following method, however I can't since I have to instantiate it. 我希望能够将元组传递给以下方法,但是由于必须实例化它,因此无法这样做。
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;
}
As I said in the comments, I'm trying to build a bare bone ORM, I am only interested in the mapping to objects part. 正如我在评论中说的那样,我正在尝试构建裸露的ORM,我只对映射到对象部分感兴趣。 It works as is, however it would be practical sometimes for quick queries to be able to pass a Tuple instead of a full class.
它按原样工作,但是有时快速查询能够传递元组而不是完整的类有时是实用的。
Is there any solution ? 有什么解决办法吗?
It does not work this way. 这种方式行不通。 Creating a method which will generate anything from a database is not a good solution for many reasons.
由于许多原因,创建一种可以从数据库生成任何东西的方法并不是一个好的解决方案。
A proper way to do this would be a bit more complicated. 正确的方法要复杂一些。 I think you need a factory interface, like this:
我认为您需要一个工厂接口,如下所示:
public interface IMyFactory<T> where T : new()
{
T Create ( string name );
}
then a concrete factory: 然后是一个混凝土工厂:
public class MyFactory : IMyFactory<MyClient>
{
public MyClient Create ( string name )
{
var t = new MyClient();
t.ClientName = name;
return t;
}
}
and then pass it to your method like: 然后将其传递给您的方法,例如:
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;
}
Then you could call your method as: 然后可以将您的方法调用为:
var myList = SelectFromDataBase(new MyFactory());
With this, you keep transforming data from database into an object separated from the object creation logic. 这样,您就可以将数据从数据库转换为与对象创建逻辑分离的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.