开发者

Getting the type of an object to pass to a method that accepts generics

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜