获取要传递给接受泛型的方法的对象类型
本文关键字:泛型 方法 对象 类型 获取 | 更新日期: 2023-09-27 18:06:16
我只能写伪代码,因为我不知道正确的语法。如果有的话
我想调用一个方法:
JsonConvert.DeserializeObject<Type>(string value);
返回给定的类型。
问题是我不知道如何将类型传递给该方法,因为我在构建时不知道类型。来自MVC控制器的方法是:
public JsonResult Save(string typeName, string model)
{
// Insert your genius answer here.
}
我需要在后面有我的类型,所以我可以使用DataContractSerializer来存储它。
可以使用Type.GetType()
方法。它有一个过载,接受该类型的程序集限定名的string
,并返回相应的Type
。
你的代码看起来像这样:
public JsonResult Save(string typeName, string model)
{
// My genius answer here
Type theType = Type.GetType(typeName);
if (theType != null)
{
MethodInfo mi = typeof(JsonConvert).GetMethod("DeserializeObject");
MethodInfo invocableMethod = mi.MakeGenericMethod(theType);
var deserializedObject = invocableMethod.Invoke(null, new object[] { model });
}
}
如果您在编译时不知道类型,那么您将不得不使用Reflection API来调用该方法。
这个问题以前已经有人回答过了,参见Jon's Skeet对这个问题的回答。