枚举在项目中的使用

代码
public enum AgeType
    {
        Undefined 
= 0,
        
/// <summary>
        
/// 日
        
/// </summary>
        Day,
        
/// <summary>
        
/// 星期
        
/// </summary>
        Week,
        
/// <summary>
        
/// 月
        
/// </summary>
        Month,
        
/// <summary>
        
/// 年
        
/// </summary>
        Year
    }

    
/// <summary>
    
/// 年龄类型转换器
    
/// </summary>
    public class AgeTypeConvertor
    {
        
public static string ConvertToText(AgeType status)
        {
            
switch (status)
            {
                
case AgeType.Day:
                    
return "";
                
case AgeType.Week:
                    
return "";
                
case AgeType.Month:
                    
return "";
                
case AgeType.Year:
                    
return "";
                
default:
                    
return string.Empty;
            }
        }
    }

算是在新公司的规范。现在实体类对应部分也映射为枚举,然后在枚举类里面定义个方法,可以设置枚举的字段的中文名称。然后在实体类里面,可以这样定义

private AgeType _ageType = AgeType.Undefined;
//年龄类型

下面是如何调用。例如绑定下拉框。把枚举类的中文定义的内容,绑定到下拉框中。ListItem绑了key,value,这样方便和数据库的交互。因为定义了个Udefined字段是默认,加到数据库成了NULL值的,所以要移除RemoveAt(0)第0条记录的索引。

代码
 foreach (int s in Enum.GetValues(typeof(AgeType)))
{
  ddlAgeType.Items.Add(
new ListItem(AgeTypeConvertor.ConvertToText((AgeType)s), Convert.ToString(s)));
}
     ddlAgeType.Items.RemoveAt(
0);
     ddlAgeType.SelectedIndex 
=0;

这样,就可以在下拉框显示对应的中文了。

原文地址:https://www.cnblogs.com/drek_blog/p/1657150.html