不能解析符号异常当传递运行时类型 [英] Cannot Resolve Symbol Exception When Passing Runtime Type
问题描述
我有一个JSON解串器(如下图所示),当我把它与已知的类型,工作完全正常。
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>();
不过,我想要做的是传中,在运行时设置一个类型,并用它来代替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'
所以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.
推荐答案
与仿制药使用的类型必须知道编译时。这就是为什么你不能做到这一点:
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>();
这不是用JavaScriptSerializer连接 - 这是如何工作的泛型
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:
<一个href="http://stackoverflow.com/questions/2107845/generics-in-c-using-type-of-a-variable-as-parameter">Generics在C#中,使用一个变量的类型作为参数
这篇关于不能解析符号异常当传递运行时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!