如果我有以下类(class):
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());
}
是否可以有一个字典将字符串映射到可以传递给此通用方法的类型,以便我可以查询正确的表?
例如:
Dictionary<string, type> typeMapper = new Dictionary<string, type>()
{
{"Apple", AppleType??}
};
var myType = typeMapper["Apple"];
List<Fruit> fruitList = getFruit<myType>();
最佳答案
使用 Dictionary 来存储委托(delegate)怎么样?
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"]();
关于c# - 将字符串映射到实体以与通用方法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378105/