将字符串映射到实体以与泛型方法一起使用 [英] map string to entity for using with generic method
本文介绍了将字符串映射到实体以与泛型方法一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有以下课程:
class Fruit {}
class Apple : Fruit {}
class Orange : Fruit {}
我有方法:
public List<Fruit> getFruit<T>() where T : Fruit {
List<Fruit> fruitList = new List<Fruit>();
return fruitList.AddRange(session.QueryOver<T>().List());
}
是否有可能将字符串映射为可以传递给此通用方法的类型的字典,以便我可以在正确的表上进行查询?
Is it possible to have a dictionary that maps a string to a type that can be passed to this generic method so I can query over the right table?
例如:
Dictionary<string, type> typeMapper = new Dictionary<string, type>()
{
{"Apple", AppleType??}
};
var myType = typeMapper["Apple"];
List<Fruit> fruitList = getFruit<myType>();
推荐答案
如何使用字典存储委托?
How about using Dictionary to store delegates ?
Dictionary<string, Func<List<Fruit>>> typeMapper = new Dictionary<string, Func<List<Fruit>>>()
{
{"Apple", () => { return getFruit<Apple>(); } },
{"Orange", () => { return getFruit<Orange>(); } }
};
List<Fruit> fruitList = typeMapper["Apple"]();
这篇关于将字符串映射到实体以与泛型方法一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文