0

我有的:

session.Query<Symptom>().First();

我正在尝试做的事情:

var className="Symptom"
session.Query<className>().First()

有可能以某种方式做到这一点吗?如果是的话去哪里看,因为我已经尝试过Type.GetType等,但没有成功。第二个问题是,我必须通过网络请求“类型”发送该查询语法中的我看起来很好吗?或者我错过了一些地方,我可以以某种方式从前端发送类型到服务并从数据库中获取我想要的数据。我正在使用该查询从 Nhibernate 获取数据,并且我不想对请求数据附带的所有可能类型进行硬编码。

编辑:

当我尝试 GetType 我得到:

cannot apply operator '<' to operands of type 'method group' and 'system.type'
4

1 回答 1

3

通用参数是编译类型构造。在您的情况下,您将字符串(运行实体)指定为类型名称,因此您需要在运行时通过反射创建一个封闭的泛型方法实例。

下一个代码演示了这一点:

假设我有:

public void Query<T>()
{
    Console.WriteLine("Called Query with type: {0}", typeof(T).Name);
}

现在为了用某种类型调用它,我需要创建一个具有该类型的方法实例:

//type you need to create generic version with
var type = GetType().Assembly //assumes it is located in current assembly
                    .GetTypes()
                    .Single(t => t.Name == "MyType");

//creating a closed generic method
var method = GetType().GetMethod("Query")
                      .GetGenericMethodDefinition()
                      .MakeGenericMethod(type);

//calling it on this object
method.Invoke(this, null); //will print "Called Query with type: MyType"

这是ideone的完整代码

于 2015-03-04T16:24:51.060 回答