代码之家  ›  专栏  ›  技术社区  ›  Cragly

枚举扩展方法ToDataSource

  •  2
  • Cragly  · 技术社区  · 17 年前

    我尝试向enum添加一个扩展方法,将其转换为DataTable,以便将其绑定到一个正常工作的DropDownList。

    
    public enum Response
    {
        Yes = 1,
        No = 2,
        Maybe = 3
    }
    
    

    public static DataTable ToDataSource(this Enum e) { Type type = e.GetType(); DataTable dt = new DataTable();
    dt.Columns.Add("value", typeof(Int32)); dt.Columns.Add("text", typeof(String));

    foreach (Int32 value in Enum.GetValues(type))
    {
        dt.Rows.Add(new object[] { value, Enum.GetName(type, value) });
    }
    
    return dt;
    

    }

    我已尝试创建一个新实例(Response new Response,Response.ToDataSource),但我收到一个生成错误,表示在访问之前可能未初始化该实例。

    7 回复  |  直到 17 年前
        1
  •  4
  •   JaredPar    17 年前

    不幸的是,你不能。扩展方法是一种功能,它允许您在类型的实例上调用新方法。它没有能力将此功能赋予类型本身。

    当我想添加一组方法add type level时,我通常会创建一个名为OriginalTypeNameUtil的新静态类,并在其中添加方法。例如ResponseUtil。这样,当我键入原始类型名时,类名是可见的。

        2
  •  2
  •   Ken    17 年前

    我只是做了一些类似的事情,没有扩展枚举类型,而是扩展了DataTable。

    public static DataTable FromEnum(this DataTable dt, Type enumType) {
    if (!enumType.IsEnum) { throw new ArgumentException("The specified type is not a System.Enum."); }
    DataTable tbl = new DataTable();
    string[] names = Enum.GetNames(enumType);
    Array values = Enum.GetValues(enumType);
    List<string> enumItemNames = new List<string>();
    List<int> enumItemValues = new List<int>();
    try {
        // build the table
        tbl.Columns.Add(new DataColumn("Value", typeof(string)));
        tbl.Columns.Add(new DataColumn("Text", typeof(string)));
        // Get the enum item names (using the enum item's description value if defined)
        foreach (string enumItemName in names) {
            enumItemNames.Add(((Enum)Enum.Parse(enumType, enumItemName)).ToDescription());
        }
        // Get the enum item values
        foreach (object itemValue in values) {
            enumItemValues.Add(Convert.ToInt32(Enum.Parse(enumType, itemValue.ToString())));
        }
        // Make sure that the data table is empty
        tbl.Clear();
    
        // Fill the data table
        for (int i = 0; i <= names.Length - 1; i++) {
            DataRow newRow = tbl.NewRow();
            newRow["Value"] = enumItemValues[i];
            newRow["Text"] = enumItemNames[i];
            tbl.Rows.Add(newRow);
        }
    }
    catch {
        tbl.Clear();
        tbl = dt;
    }
    // Return the data table to the caller
    return tbl;
    

    }

    它的名字是这样的:

    DataTable tbl = new DataTable().FromEnum(typeof(YourEnum));
    
        3
  •  1
  •   bobbymcr    17 年前

    似乎您只需要一个真正的静态方法和一个“类似枚举”的类:

    public class Response
    {
        public static readonly Response Yes = new Response(1);
        public static readonly Response No = new Response(2);
        public static readonly Response Maybe = new Response(3);
    
        int value;
    
        private Response(int value)
        {
            this.value = value;
        }
    
        public static DataTable ToDataSource()
        {
            // ...
        }
    }
    
        4
  •  1
  •   Charles Bretana    17 年前

    如果使用模拟枚举的结构:

       public struct Response
       {
         private int ival;
         private Response() {} // private ctor to eliminate instantiation
         private Response(int val) { ival = val; }
         private static readonly Response Yes = new Response(1);
         private static readonly Response No = new Response(2);
         private static readonly Response Maybe= new Response(3);
         // etc...  ...for whatever other functionality you want.... 
       }
    

    然后这个结构的功能完全(接近完全!)像一个枚举,您可以向它添加扩展方法。。。

        5
  •  1
  •   Pierre-Alain Vigeant    17 年前

    但是,您可以创建一个接受枚举的泛型函数,并从中创建一个表。

    public static DataTable CreateDataSource<TEnum>()
    {
        Type enumType = typeof(TEnum);
    
        if (enumType.IsEnum) // It is not possible to do "where TEnum : Enum"
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name");
            table.Columns.Add("Value", enumType);
    
            foreach (var value in Enum.GetValues(enumType))
            {
                table.Rows.Add(Enum.GetName(enumType, value), value);
            }
    
            return table;
        }
        else
            throw new ArgumentException("Type TEnum is not an enumeration.");
    }
    
        6
  •  0
  •   JeffreyABecker    17 年前

        7
  •  -1
  •   Hux    17 年前
    string[] names = Enum.GetNames(typeof(Test));
    
    Array test = Enum.GetValues(typeof(Test));
    var vals = test.Cast<int>();
    
    var source = from n in names
                 from v in vals
                 select new
                 {
                     Text = n,
                     Value = v
                 };
    

    未测试,但速度很快:)

    推荐文章