【发布时间】:2016-03-27 10:57:29
【问题描述】:
我有一个具有以下结构的类
public class GenericEntity<T>
where T : BaseClass
{
T Property {get; set;}
}
我有几个BaseClass 的具体实现,我正在使用这些具体实现来实例化GenericEntity 类型的对象
例如var entity = new GenericEntity<DerivedClass>()
我通过将对象序列化为 JSON(使用 Newtonsoft)将这个实体推送到消息传递框架中。在另一端,我正在从消息队列中提取该消息 (JSON),并尝试使用 JsonSerializerSettings TypeNameHandling.All 将消息反序列化为 GenericEntity<BaseClass> 类型。但是在反序列化的时候,会抛出JsonSerializationException的细节
在 JSON 中指定的类型 'NewtonsoftPlayground.GenericEntity
1[[NewtonsoftPlayground.DerivedClass, NewtonsoftPlayground, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], NewtonsoftPlayground, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'NewtonsoftPlayground.GenericEntity1[[NewtonsoftPlayground.BaseClass, NewtonsoftPlayground, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], NewtonsoftPlayground, Version=1.0.0.0, Culture=neutral , PublicKeyToken=null'。
我怎样才能做到这一点?还是我不应该使用泛型?如果是这样,我会在从队列中提取消息后到处写类型转换,这是我试图避免的。
【问题讨论】:
标签: c# generics json.net covariance