[英]C# Generics on Auto-Implemented Property Classes
I created a property class representing the table schema of my SQLite database. 我创建了一个代表我的SQLite数据库表架构的属性类。 Each attribute in the class become one attribute in the database.
类中的每个属性都将成为数据库中的一个属性。
class SQLiteTables
{
public class tblPerson
{
[PrimaryKey, AutoIncrement]
public int PersonID { get; set; }
public string PersonFirstName { get; set; }
public string PersonMiddleName { get; set; }
public string PersonLastName { get; set; }
}
public class tblSchedule
{
[PrimaryKey, AutoIncrement]
public int ScheduleID { get; set; }
public string ScheduleDescription { get; set; }
public DateTime ScheduleStart { get; set; }
public DateTime ScheduleEnd { get; set; }
}
//18 more table definitions below
}
Now, to retrieve some data from a table, 现在,要从表中检索一些数据,
public void GetPersonList()
{
List<tblPerson> lstTemp = dbConn.Table<tblPerson>().ToList<tblPerson>();
// Some 20 lines of code here
}
I want to avoid writing type-specific methods, well it's kind of a tedious task. 我想避免编写特定于类型的方法,这是一个繁琐的任务。 I want to create a reusable method which can retrieve data on any table using generics implementation.
我想创建一个可重用的方法,该方法可以使用泛型实现检索任何表上的数据。 How can I achieve this?
我该如何实现?
EDIT I am working on a Windows Phone 8 platform. 编辑我正在Windows Phone 8平台上工作。
This should work for what you're doing. 这应该适合您的工作。
public List<T> GetItems<T>()
{
return dbConn.Table<T>().ToList<T>();
}
public IEnumerable<T> GetItems<T>() where T: new()
{
lock (locker) {
return dbCon.Table<T> ().ToArray ();
}
}
I think the key is the ":new()" at the end 我认为关键是最后的“:new()”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.