我是 C# 的新手,想知道如何实现下面描述的功能。目前这不是在指定的行编译。我希望代码执行的操作是:
遍历每个KVP, 使用键字符串作为表名查询数据库 返回列表
var dbCon = dbConnectionFactory.OpenDbConnection();
Dictionary<string, Type> ibetDic = getFromSomeWhere();
foreach (KeyValuePair<string, Type> entry in ibetDic)
{
Type type = entry.Value;
var typedRedisClient = redis.GetTypedClient<type>();/*not compiling here*/
String sql = "USE ibet SELECT * FROM " + entry.Key;
var itemList = dbCon.SqlList<type>(sql);/*not compiling here*/
foreach (var tableRow in itemList )
{
//store with redistypedclient
}
}
最佳答案
最接近我找到的答案,但这意味着我必须传入类型,而不是像我上面想要的那样通过字典访问它:
public void GetAndStoreIntKey<T>(string tableName) where T : IHasId<int>
{
var dbCon = dbConnectionFactory.OpenDbConnection();
String sql = "USE ibet SELECT * FROM " + tableName;
var items = dbCon.SqlList<T>(sql);
var typedRedisClient = redis.As<T>();
foreach (T item in items)
{
typedRedisClient.SetEntry(UrnId.CreateWithParts<T>(new string[] {item.Id + ""}), item);
}
}
用法如:
GetAndStoreIntKey<Sport>("Sport");
关于dynamic - 在 C# 中获取动态类型的 ServiceStack.redis 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583785/