【发布时间】:2011-07-23 02:10:29
【问题描述】:
我正在使用泛型,但我觉得自己太过分了,想知道 StackOverflow 是否可以提供帮助?我认为使用我的代码的简化版本来解释我的问题会容易得多,而不是 A 类扩展 B 类的抽象示例等。如果它过于简单,我深表歉意。
我的 C# (Windows Phone 7 .NET 3.5) 应用程序触发对 Web 服务的请求,并使用 XML 响应填充从基类 WebServiceResult 派生的 Result 对象。最初它触发了请求,解析了响应,然后调用方法将 Result 类型转换为它所期望的结果。我认为既然我们知道我们期望什么类型的结果,这是没有意义的,并试图使用泛型来解决这个问题。
// abstract class to do the raw http response handling
public abstract class WebServiceResultParser<T> where T : WebServiceResult {
T result;
public WebServiceResultParser(T result) {
this.result = result;
}
protected abstract bool Parse(String response);
private bool ParseHttpResponse(HttpWebResponse httpWebResponse){
//some logic to get http response as string
result.GetParser<T>().Parse(http_response_as_string);
return true;
}
}
// abstract class that models a webservice result
public abstract class WebServiceResult {
protected internal abstract WebServiceResultParser<T> GetParser<T>()
where T : WebServiceResult;
}
“注册”网络服务请求的实现
// knows how to parse the xml
public class RegistrationResultParser : WebServiceResultParser<RegistrationResult>{
private RegistrationResult result;
public RegistrationResultParser(RegistrationResult result)
: base(result) {
this.result = result;
}
protected override bool Parse(String response){
//some logic to extract customer number
result.CustomerNumber = customerNumber;
return true;
}
}
// stores the result
public class RegistrationResult : WebServiceResult {
public String CustomerNumber { get; internal set; }
protected internal override WebServiceResultParser<T> GetParser<T>() {
return new RegistrationResultParser(this); // <--- Compiler error here
}
}
编译器错误提示
无法将类型“RegistrationResultParser”隐式转换为“
WebServiceResultParser<T>”
这是我能走的最远的地方,而不是绕圈子。任何建议、进一步阅读或 cmets 将不胜感激。
干杯, 阿拉斯代尔。
【问题讨论】: