枚举类型判断存在
Enum.TryParse("thevalue", out TestEnum result);
这样判断 会存在说 如果 "thevalue" 为数字的 时候 仍然会被转化成功,即使它并没有在枚举中没初始化,以下是该方法的解释:
1 // 2 // Summary: 3 // Converts the string representation of the name or numeric value of one or more 4 // enumerated constants to an equivalent enumerated object. The return value indicates 5 // whether the conversion succeeded. 6 // 7 // Parameters: 8 // value: 9 // The case-sensitive string representation of the enumeration name or underlying 10 // value to convert. 11 // 12 // result: 13 // When this method returns, result contains an object of type TEnum whose value 14 // is represented by value if the parse operation succeeds. If the parse operation 15 // fails, result contains the default value of the underlying type of TEnum. Note 16 // that this value need not be a member of the TEnum enumeration. This parameter 17 // is passed uninitialized. 18 // 19 // Type parameters: 20 // TEnum: 21 // The enumeration type to which to convert value. 22 // 23 // Returns: 24 // true if the value parameter was converted successfully; otherwise, false. 25 // 26 // Exceptions: 27 // T:System.ArgumentException: 28 // TEnum is not an enumeration type. 29 public static bool TryParse<TEnum>(string? value, out TEnum result) where TEnum : struct;
所以这里推荐使用:IsDefined 方法去做存在判断。
1 // 2 // Summary: 3 // Returns a Boolean telling whether a given integral value, or its name as a string, 4 // exists in a specified enumeration. 5 // 6 // Parameters: 7 // enumType: 8 // An enumeration type. 9 // 10 // value: 11 // The value or name of a constant in enumType. 12 // 13 // Returns: 14 // true if a constant in enumType has a value equal to value; otherwise, false. 15 // 16 // Exceptions: 17 // T:System.ArgumentNullException: 18 // enumType or value is null. 19 // 20 // T:System.ArgumentException: 21 // enumType is not an Enum. -or- The type of value is an enumeration, but it is 22 // not an enumeration of type enumType. -or- The type of value is not an underlying 23 // type of enumType. 24 // 25 // T:System.InvalidOperationException: 26 // value is not type System.SByte, System.Int16, System.Int32, System.Int64, System.Byte, 27 // System.UInt16, System.UInt32, or System.UInt64, or System.String. 28 public static bool IsDefined(Type enumType, object value);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)