Cannot Resolve Symbol Exception When Passing Runtime Type

牧云@^-^@ 提交于 2019-12-08 06:54:28

问题


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



来源:https://stackoverflow.com/questions/15298178/cannot-resolve-symbol-exception-when-passing-runtime-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!