比较有用的枚举方法

本文介绍了一个用于将驼峰命名法转换为句子的方法,并提供了一个获取枚举值描述的实用工具。通过这些工具可以更好地管理和展示代码中的枚举和变量命名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// <summary>
/// 将骆驼命名法的单词转为句子. 如NotSent-->Not Sent
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static String ConvertCamelToSentence(string str)
{
if (string.IsNullOrEmpty(str)) { return str; }
str = str.Trim();
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < str.Length; i++)
{
string s = str.Substring(i, 1);
if (s[0] >= 'a' && s[0] <= 'z'){
sb.Append(s);
}else
{
sb.Append(" "+s);
}
}
return sb.ToString().Trim();
}

public static String GetEnumString(Type e) {
return Enum.GetName(e, 1);
}


/// <summary>
/// 得到某一枚举的值对应的描述/定义字符串
/// 如: [Description("Sent Failed")]
/// Failed=-1,
/// 即得到 value:-1, desc:Sent Failed (如没有定义Description, 将得到Failed)
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <param name="enumValue">枚举的值,object类型只是避免转换,其实只能是int类型</param>
/// <returns></returns>
public static String GetEnumDescByValue(Type enumType, object enumValue) {
NameValueCollection nvc = GetNVCFromEnumValue(enumType);
foreach (string s in nvc.AllKeys)
{
if (nvc[s] == enumValue.ToString())
return s;
}
return null;
}

/// 从枚举类型和它的特性读出并返回一个键值对
/// Type,该参数的格式为typeof(需要读的枚举 类型)
/// 键值对
public static NameValueCollection GetNVCFromEnumValue(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute aa = (DescriptionAttribute)arr[0];
strText = aa.Description;
}
else
{
strText = field.Name;
}
nvc.Add(strText, strValue);
}
}
return nvc;
}

### 枚举方法简介 枚举(`enum`)是一种特殊的数据类型,在 C# 中用于定义一组命名的常量。通过使用 `enum`,可以提高代码的可读性和维护性[^1]。 #### 定义枚举 在 C# 中,可以通过关键字 `public enum` 来声明一个枚举类型。例如: ```csharp public enum OperEnum { None = 1, User = 2, Admin = 3 } ``` 上述代码定义了一个名为 `OperEnum` 的枚举类型,其中包含了三个成员:`None`, `User`, 和 `Admin`,分别对应整数值 1、2 和 3。 #### 将枚举绑定到 ComboBox 控件 为了将枚举值显示在一个下拉列表控件(如 `ComboBox`),通常需要将其转换为字符串数组或键值对集合。以下是实现此功能的一个示例: ```csharp using System; using System.Collections.Generic; using System.Windows.Forms; public class EnumToComboBoxExample : Form { private ComboBox comboBox; public EnumToComboBoxExample() { InitializeComponents(); BindEnumToComboBox<OperEnum>(comboBox); } private void InitializeComponents() { comboBox = new ComboBox { Parent = this }; } public static void BindEnumToComboBox<T>(ComboBox comboBox) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); var list = new List<KeyValuePair<int, string>>(); foreach (var value in Enum.GetValues(typeof(T))) { int key = Convert.ToInt32(value); string name = Enum.GetName(typeof(T), value); list.Add(new KeyValuePair<int, string>(key, name)); } comboBox.DisplayMember = "Value"; comboBox.ValueMember = "Key"; comboBox.DataSource = new BindingSource(list, null); } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new EnumToComboBoxExample()); } } ``` 在此代码片段中,创建了一个窗体应用程序,并演示如何将自定义枚举类型的值加载至 `ComboBox` 下拉框中。具体来说,函数 `BindEnumToComboBox<T>` 接收泛型参数并验证其是否为有效的枚举类型;随后遍历该枚举的所有可能取值,构建由键值对组成的列表,最后设置数据源属性完成绑定操作。 ### 枚举的优势 利用枚举代替原始整数或者字符串来表示固定选项集具有诸多好处: - **增强语义表达力**:相比单纯依赖数字编码方案而言,采用具名标识符能够显著提升程序逻辑描述能力。 - **减少错误发生几率**:由于编译器会对非法赋值发出警告甚至报错提示,因此有助于避免因拼写失误而导致运行期异常情况的发生。 - **简化调试过程**:当查看变量当前状态时可以直接看到有意义的名字而非难以理解的具体数值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值