我有这种非工作方法。其中类型 T 有时可以是“字符串”。当然反序列化没有意义,所以我想检查一下 T 是否是一个字符串,并在反序列化之前返回结果。我怎样才能得到这个?
private T SendRequest<T, E>(string url, E body, Guid? token)
{
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = body != null ? "POST" : "GET";
request.ContentType = "application/json";
if (token != null)
{
request.Headers.Add("Token", token.ToString());
}
if (body != null)
{
var bodyWriter = new StringWriter();
_serializer.Serialize(new JsonTextWriter(bodyWriter), body);
var bytes = Encoding.UTF8.GetBytes(bodyWriter.ToString());
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = request.GetResponse())
{
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
var str = responseStreamReader.ReadToEnd();
if (typeof(T) == typeof(String))
{
return str; // <-- Cannot convert expression type 'string' to return type 'T'
}
return _serializer.Deserialize<T>(new JsonTextReader(new StringReader(str)));
}
}
}