[英]Conditional type argument in C#
I would like to deserialize object into a given class type, depending on whether the ajax response was successful or not. 我想将对象反序列化为给定的类类型,具体取决于ajax响应是否成功。
So I written the following method: 所以我写了以下方法:
public IAjaxResponse GetResponse<TOk, TFail>()
{
var responseJson = this.response as Dictionary<string, object>;
object obj = null;
if ((string)responseJson["status"] == "ok")
obj = JsonConvert.DeserializeObject<TOk>(responseJson);
else
obj = JsonConvert.DeserializeObject<TFail>(responseJson);
return (IAjaxResponse)obj;
}
Now it's pretty straightforward to use: 现在使用起来非常简单:
var response = GetResponse<ClassWhenOk, ClassWhenFail>();
if (response is ClassWhenFail responseFail) {
Error.Show(responseFail.message);
return;
}
[..]
Now my problem is : sometimes, there are generic responses which happend to be always 'ok' status so I don't want to use the second type argument for failed status. 现在我的问题是 :有时,有些通用响应恰好总是为“ ok”状态,因此我不想将第二种类型的参数用于失败状态。
So I would want to use something like that: 所以我想使用这样的东西:
\/ notice one type argument
GetResponse<ClassWhenOk>();
This is not allowed though since using this generic method requires 2 type arguments. 但这是不允许的,因为使用此通用方法需要2个类型参数。
So here comes my question : 所以这是我的问题 :
Can I somehow mark the second type argument ( TFail
) as 'not required'? 我可以以某种方式将第二种类型的参数(
TFail
)标记为“不需要”吗? Or should I rather go for different approach? 还是我应该选择其他方法?
Your code just doesn't make sense. 您的代码只是没有意义。 The
responseJson
object cannot be a Dictionary<string, string>
and a string
at the same time. responseJson
对象不能同时是Dictionary<string, string>
和一个string
。 It would be good to be able to post real code for us to work from. 能够发布真实的代码供我们工作将是一件好事。
Here's a refactored example that does compile, but needs some work to behave properly at run-time. 这是一个经过编译的重构示例,但是需要一些工作才能在运行时正常运行。 Nevertheless, all you need is an alternative overload to make this work.
但是,您所需要做的就是替代重载才能完成此工作。
public IAjaxResponse GetResponse<TOk, TFail>(string response)
{
var responseJson = new Dictionary<string, object>();
object obj = null;
if ((string)responseJson["status"] == "ok")
obj = Newtonsoft.Json.JsonConvert.DeserializeObject<TOk>(response);
else
obj = Newtonsoft.Json.JsonConvert.DeserializeObject<TFail>(response);
return (IAjaxResponse)obj;
}
public IAjaxResponse GetResponse<TOk>(string response)
{
return (IAjaxResponse)Newtonsoft.Json.JsonConvert.DeserializeObject<TOk>(response);
}
The second method could even be this: 第二种方法甚至可以是:
public IAjaxResponse GetResponse<TOk>(string response)
{
return GetResponse<TOk, FailDontCare>(response);
}
That just avoids code duplication. 那只是避免了代码重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.