Those days I am programming to store settings in sqlite database. I am define every setting to a class, But it is not easy to write every funciton to add every new setting to database.So I use generics type to do it.
private int AddNewItem<T>(string table, T t) { StringBuilder sb = new StringBuilder("insert into "); sb.Append(table); sb.Append(" values ("); PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); List paramlist = new List (properties.Length); foreach (PropertyInfo property in properties) { sb.Append("@"); sb.Append(property.Name); sb.Append(","); paramlist.Add(new SQLiteParameter("@" + property.Name, property.GetValue(t, null))); } sb.Length -= 1;//remove last "," sb.Append(")"); paramlist[0].Value = null;//it must be "id" colume return SQLiteHelper.ExecuteIns(sb.ToString(), paramlist.ToArray()); }
For example,the table is created by sql
"CREATE TABLE IF NOT EXISTS [settings]( id INTEGER PRIMARY KEY AUTOINCREMENT,key TEXT,value TEXT);"
And the class is defined as
class SettingItem
{
public long id { get; set; }
public string key {get;set;}
public string value { get; set; }
}
Just add a new key-value pair by calling
private int AddNewKeyValue(SettingItem item)
{
return AddNewItem<SettingItem>("[settings]", item);
}
Related posts:

Вы всегда публикуете только лучшую информацию. У вас просто супер блог. Спасибо