我想建立一个通用的方法来调用像Bing地图这样的许多Web API。对于这个问题,我使用的课程来自:Problem with deserializing JSON on datamember "__type",这很好。如何将对象转换为未知的泛型?
我不知道究竟怎么投ser.ReadObject(a.Result)到我给的泛型参数的类型,在这种情况下LocationQueryResponse。
public static void GetResponse<TDataContract>(Uri uri, Action<TDataContract> callback)
where TDataContract : IDataContract, new()
{
var contract = new TDataContract();
var contractType = contract.GetType();
var wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
var ser = new DataContractJsonSerializer(typeof(TDataContract));
callback(Convert.ChangeType(ser.ReadObject(a.Result), contractType));
}
};
wc.OpenReadAsync(uri);
}
现在我得到这个错误: 类型参数“TDataContract”不能与使用“为”经营者,因为它没有一个类类型约束,也不是一个“类”约束基础设施
每个与Web API进行通信的类都继承了IDataContract接口。 任何人都可以提供帮助吗?
谢谢
大卫
你试过TDataContract:IDataContract,new(),class吗?虽然我认为你可以以更简单的方式做到这一点...... – lintmouse
什么是更简单的方法? –
使用与泛型一起使用的JSON序列化程序怎么样?可能是这样的:https://msdn.microsoft.com/en-us/library/bb355316(v=vs.110).aspx – lintmouse