Cannot Resolve Symbol Exception When Passing Runti

2019-06-01 16:26发布

问题:

I have a JSON deserializer (shown below) which works perfectly fine when I call it with a known type.

public static T Deserialize<T>(this object obj)
{
    var javaScriptSerializer = new JavaScriptSerializer();

    return (obj != null) ?
        javaScriptSerializer.Deserialize<T>(obj.ToString()) :
        default(T);
}

So this call will work:

var newExampleTypeX = exampleJsonString.Deserialize<ExampleTypeX>();

However, what I'm trying to do is pass in a type which is set at runtime and use it in place of the "ExampleTypeX". When I do I get the following compilation error:

Cannot resolve symbol 'someType'

So the declaration of someType looks like so (this is a simplified version):

var someType = typeof(ExampleTypeX);
var newExampleTypeX = message.Deserialize<someType>();

Should I be altering my Deserialize extension method somehow, or altering how I pass in the runtime type? If so then how do I achieve that.

回答1:

Type used with generics has to be know compile-time. That's why you can't do that:

var someType = typeof(ExampleTypeX);
var newExampleTypeX = message.Deserialize<someType>();

It's not connected with JavaScriptSerializer - that's how generics work.

If you really need to, you can use reflection to bypass that, but I don't think you should.

You can read more about using reflection with generic types and extension method in that two questions:

Generics in C#, using type of a variable as parameter

Reflection to Identify Extension Methods