如何返回具有通用属性的C#Web服务? [英] How do I return a C# web service that has a generic property?
问题描述
我正在创建一个Web服务,并且希望对返回数据更加优雅,而不是拥有许多消费者需要检查的属性.
I am creating a web service, and want to be a bit more elegant with the return data, instead of having lots of properties that the consumer needs to check.
根据幕后生成的数据,我需要能够返回错误数据或用户期望的数据.
Depending on what data is generated behind the scenes, I need to be able to return error data, or the data the consumer was expecting.
我没有一个大的平面对象,而是在需要时填充属性,并让用户检查成功"标志,我希望将单个属性Data用作错误类的实例,或者成功类的实例.
Instead of having a large flat object, and filling the properties when needed, and letting the user check a 'success' flag, I'd like a single property, Data, to be either an instance of an error class, or an instance of a success class.
这是我想做的事情
class ItemResponse
{
public bool Success { get; set; }
public T Data{ get; set; }
}
if( /*acceptance criteria*/ )
{
ItemResponse<SuccessData> resp = new ItemResponse<SuccessData>();
resp.Data = new SuccessData();
}
else
{
ItemResponse<ErrorData> resp = new ItemResponse<ErrorData>();
resp.Data = new ErrorData();
}
return resp;
public class SuccessData
{
}
public class ErrorData
{
}
然后让web方法返回具有通用属性的对象.
Then have the web method return the object, with the generic property.
这是可能的,如果可以的话,鉴于必须正确键入webmethod返回类型,我该怎么办?
Is this possible, and if so, how would I do it, given that the webmethod return type has to be typed correctly?
推荐答案
泛型是在编译期间添加类型安全性的工具.因此,必须在编译时知道该类的使用者使用的具体类型.如果您创建函数
Generics are a tool for adding type safety during compile time. Consequently, the concrete type used by the consumer of the class must be known at compile time. If you create a function
List<T> myFunction<T>() {...}
...然后在调用它时需要指定T
,例如
...then you need to specify T
when calling it, e.g.
var myResult = myFunction<int>();
...这使得在编译时知道具体类型. (即使您未指定T
(因为可以推断出它),具体类型在编译时也是 .)
...which makes the concrete type known at compile time. (Even if you don't specify T
because it can be infered, the concrete type is also known at compile time.)
但是,您希望在run-time
处确定Data
的通用类型:如果发生错误,则返回ItemResponse<SuccessData>
,否则返回ItemResponse<ErrorData>
.那不是泛型的工作原理.
You, however, want the generic type of Data
to be determined at run-time
: If an error occured, you return an ItemResponse<SuccessData>
, otherwise an ItemResponse<ErrorData>
. That's just not how generics work.
这篇关于如何返回具有通用属性的C#Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!