将字符串映射到实体以与通用方法一起使用

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());

}

是否可以有一个字典将字符串映射到可以传递给此通用方法的类型,以便我可以查询正确的 table?

例如:

Dictionary<string, type> typeMapper = new Dictionary<string, type>()
{
 {"Apple", AppleType??}
};

var myType = typeMapper["Apple"];
List<Fruit> fruitList = getFruit<myType>();

您可以使用反射创建未知类型的实例。这可以使用 Activator.CreateInstance(typeof(Apple)) 来完成,例如。 话虽如此,您根本不需要泛型:

Dictionary<string, Type> typeMapper = new Dictionary<string, Type>()
{
    {"Apple", typeof(Apple)}
};

var myType = typeMapper["Apple"];
var apple = Activator.CreateInstance(myType);

编辑:但是这个方法不是类型安全的,所以你得到的只是一个 object 而不是你的具体类型。但是,您可以将结果转换为 Fruit 并将其添加到列表中:

fruitList.Add((Fruit) apple);

您可以使用反射调用具有 Type

的泛型方法
[Fact]
public void Test_WithTypesAndReflection_Succeeds()
{
    var typeMapper = new Dictionary<string, Type>()
    {
        { "Apple", typeof(Apple) },
        { "Orange", typeof(Orange) }
    };

    var method = (
        from m in this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
        where m.Name == "GetFruit"
        where m.GetParameters().Count() == 0
        select m).Single();

    var result = (IEnumerable<Fruit>)method
        .MakeGenericMethod(typeMapper["Apple"])
        .Invoke(this, null);
}

private IEnumerable<Fruit> GetFruit<T>() where T : Fruit
{
    return Enumerable.Empty<T>().Cast<Fruit>();
}

使用字典来存储委托怎么样?

    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"]();