Skip to main content
 首页 » 编程设计

c#之在 C# 中使用枚举作为属性类

2024年02月13日13tuyile006

我是 C# 的新手,我想要实现的是以下内容。

我有一个带有 Type 属性的 Action 类,它采用以下值之一,Button 或 Link:

public class Action 
{ 
    public ActionType Type { get; set; } 
 
} 
 
 
public enum ActionType 
{ 
    Button, 
    Link 
}  

我正在使用 WebAPI,现在我使用以下模拟列表来检查返回的数据

private static IList<Alert> alerts = new List<Alert>() 
{ 
    new Alert() 
    { 
        Description = "You have cancelled your subscription", 
        Actions = new Action[] 
        { 
            new Action() 
            { 
                Type = ActionType.Button 
            } 
        } 
 
    } 
}; 

当我在浏览器中测试时,我得到

"Actions": [ 
 
    { 
        "Type": 0 
    } 
 
] 

我想要实现的是类型属性的返回值“按钮”或“链接”。我尝试在定义 ActionType 的地方做这样的事情:

public enum ActionType 
{ 
    Button = "button", 
    Link   = "link" 
} 

但我收到以下错误消息“无法将类型‘string’隐式转换为‘int’。

如何修复上述错误?

请您参考如下方法:

您需要使用自己的 JSON 序列化,例如使用 Json.net,它具有相应的属性。看看这个:

class Example 
{ 
  [JsonConverter(typeof(StringEnumConverter))] 
  public ActionType ActionType { get; set; } 
} 
 
var serializedObject = JsonConvert.SerializeObject(new Example(), Formatting.Indented);