I can only write this in pseudo-code since I don't know the correct syntax.. If there is one.
I have a method I want to call:
JsonConvert.Deseria开发者_运维百科lizeObject<Type>(string value);
Which would return the given type.
The problem is that I don't know how to pass the type to that method since I won't know the type at build time. The method from my MVC Controller would be:
public JsonResult Save(string typeName, string model)
{
// Insert your genius answer here.
}
I need to have my type later on so I can use a DataContractSerializer to store it.
Any help would be appreciated.
You can use the Type.GetType()
method. It has an overload that accepts a string
of the assembly-qualified name of the type, and returns the corresponding Type
.
Your code would look something like this:
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 });
}
}
If you don't know the type at compile time, then you'll have to use the Reflection API to invoke the method.
This has been answered before, see Jon's Skeet's answer on this question for example.
精彩评论