如何在C#枚举中存储多值(状态名称与重定向URL)
为C#枚举自定义特性存储重定向URL
你可以通过自定义特性来实现和[Description]特性一致的用法,不用额外声明类或依赖配置文件,具体步骤如下:
1. 定义自定义URL特性
先创建一个继承自Attribute的特性类,专门用来保存枚举值对应的重定向URL:
public class RedirectUrlAttribute : Attribute { public string Url { get; } public RedirectUrlAttribute(string url) { Url = url; } }
2. 给枚举值标记双特性
在你的UserState枚举中,给每个值同时添加[Description]和[RedirectUrl]特性:
public enum UserState { [Description("未激活")] [RedirectUrl("/Account/Activate")] Inactive, [Description("已锁定")] [RedirectUrl("/Account/Locked")] Locked, [Description("正常使用")] [RedirectUrl("/Dashboard")] Normal }
3. 编写扩展方法读取特性值
和读取Description的逻辑类似,写一个通用扩展方法来读取枚举值上的RedirectUrl特性:
public static class EnumExtensions { // 你已有的读取Description的方法 public static string GetDescription(this Enum value) { var field = value.GetType().GetField(value.ToString()); var attribute = field?.GetCustomAttribute<DescriptionAttribute>(); return attribute?.Description ?? value.ToString(); } // 新增读取重定向URL的方法 public static string GetRedirectUrl(this Enum value) { var field = value.GetType().GetField(value.ToString()); var attribute = field?.GetCustomAttribute<RedirectUrlAttribute>(); return attribute?.Url ?? string.Empty; } }
4. 实际使用示例
直接通过枚举值调用扩展方法即可获取对应的状态名称和重定向URL:
UserState currentState = UserState.Inactive; string stateName = currentState.GetDescription(); // 输出:未激活 string redirectUrl = currentState.GetRedirectUrl(); // 输出:/Account/Activate
内容的提问来源于stack exchange,提问作者Kaiwinta
相关产品推荐
相关产品推荐

