首页 新闻 赞助 找找看

C#枚举 转换

0
悬赏园豆:20 [待解决问题]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<SelectListItem> test = ToSelectListItem(PaymentEnum.ByAmount);
            Console.ReadKey();
        }

        public static List<SelectListItem> ToSelectListItem(Enum valueEnum)
        {                    
            return (from int value in Enum.GetValues(valueEnum.GetType())
                    select new SelectListItem
                    {
                        Text = GetEnumDescription(xxx),//问题就是这里,
              //我这里想把Text显示成枚举的description 但是参数不知道怎么写 Value
= Enum.GetName(valueEnum.GetType(), value), Selected = Enum.GetName(valueEnum.GetType(), value) == valueEnum.ToString() ? true : false }).ToList(); } public static string GetEnumDescription(Enum enumSubitem) { string strValue = enumSubitem.ToString(); FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue); if (fieldinfo == null) return string.Empty; Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return strValue; } else { DescriptionAttribute da = (DescriptionAttribute)objs[0]; return da.Description; } } } public enum PaymentEnum { [Description("按日期")] ByDate, [Description("按票量")] ByTicket, [Description("按产量")] ByAmount } public class SelectListItem { public bool Selected { get; set; } public string Text { get; set; } public string Value { get; set; } } }

以上将枚举转成selectlist是网上找的,但是想替换里面的Text赋值,不知道怎么传参,GetEnumDescription是封装的获取枚举的description方法,接收参数为枚举。

问题是:怎么讲遍历枚举的项转成对应的枚举,已知type,Enum.Parse(typeof(xx),xx),这个方法返回的是object,参数中用不了

麦田清风的主页 麦田清风 | 初学一级 | 园豆:7
提问于:2016-02-22 21:34
< >
分享
所有回答(1)
0

PaymentEnum pe=(PaymentEnum ) Enum.Parse(typeof(xx),xx);

就可以了。

ensleep | 园豆:1682 (小虾三级) | 2016-02-23 08:57

  嗯,实例的话可以,但封装好的ToSelectListItem方法中,用什么参数呢?

支持(0) 反对(0) 麦田清风 | 园豆:7 (初学一级) | 2016-02-23 09:47

@new_ITP: 


public static string GetEnumDescription(Enum enumSubitem)
{
string strValue = enumSubitem.ToString();
Type type = enumSubitem.GetType();
var attr =(DescriptionAttribute) type.GetCustomAttributes(typeof(DescriptionAttribute) ,false).FirstOrDefault();
if(attr == null)
{
return "";
}

return attr.Description;
}

支持(0) 反对(0) ensleep | 园豆:1682 (小虾三级) | 2016-02-23 19:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册