Skip to main content
 首页 » 编程设计

C#之通过 web 服务公开枚举类型

2024年01月29日25落叶

好的,我在尝试通过我的网络服务公开此枚举类型时遇到了重大问题。就公开它们而言,它的功能与我的自定义类不同。

服务器端:

[DataContractAttribute] 
public enum EventReportType {EventAutoContract, DailyAutoContract, EventFunctionSheet } 

客户端:

// For a custom class I would do: 
ServerRef.MyClass maclass = new ServerRef.MyClass(); 
// but the following does not work. 
ServerRef.EventReportType myenum = new ServerRef.EventReportType(); 
enum test = new ServerRef.EventReportType(); 

我认为它甚至不在 WSDL 中,那么我如何才能正确公开它呢? 我将如何消费和使用它?

请也看看我的其他问题以获得赏金:REST with nullable types?

请您参考如下方法:

因为该类型是一个enum,您不需要创建它的实例,您可以访问值的静态表示。

例如,

var value = EventReportType.EventAutoContract; 

但一般来说,除非需要,否则您不会将值赋给变量,您只会显式地使用它;因此,假设调用一个服务方法,该方法接受来自该类型的枚举值:

myServiceCall(EventReportType.EventAutoContract); 

请注意,您也不需要明确拼出 DataContractAttribute,这可以简写为 DataContract,而且,您可能需要每个 enum 成员也将使用 EnumMember 属性进行扩充。所以……

[DataContract] 
public enum EventReportType  
{ 
    [EnumMember] 
    EventAutoContract,  
    [EnumMember] 
    DailyAutoContract,  
    [EnumMember] 
    EventFunctionSheet  
} 

可以找到在数据契约中使用枚举类型的引用here .最终,如果您的 enum 被正确定义并在暴露给客户端的服务中的某处使用,那么将生成 enum。