枚举扩展方法 –到数据源

发布于 2024-08-04 03:11:42 字数 796 浏览 2 评论 0原文

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


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

公共静态 DataTable ToDataSource(this Enum e) { 类型 type = e.GetType(); DataTable dt = new DataTable();
dt.Columns.Add("值", typeof(Int32)); dt.Columns.Add("文本", typeof(String));

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

return dt;

}

However is there a way that I can use the extension method on the enum itself (Response.ToDataSource) rather than having to use it hanging of a value Responce.Yes.ToDataSource?

我尝试创建一个新实例(响应新响应,response.ToDataSource,但我收到一个构建错误,指出“访问之前可能未初始化”。

I have tried to add an extension method to an enum which converts it to a DataTable so that it can be bound to a DropDownList which works fine.


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;

}

However is there a way that I can use the extension method on the enum itself (Response.ToDataSource) rather than having to use it hanging of a value Responce.Yes.ToDataSource?

I have tried creating an new instance (Response new response, response.ToDataSource but I get a build error saying that “it may not be initialised before accessing”.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

椒妓 2024-08-11 03:11:43

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

   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.... 
   }

那么这个结构的功能与枚举完全一样(接近完全!),并且您可以向它添加扩展方法...

If you use a struct that emulates an enum:

   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.... 
   }

Then this struct functions exactly (close to exactly !) like an enum, and you can add extensiuon methods to it...

送你一个梦 2024-08-11 03:11:43

无法在枚举上创建扩展方法。

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

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.");
}

It is not possible to create an extension method on an enum.

You could however create a generic function that accept enums and create a table from it.

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.");
}
昔梦 2024-08-11 03:11:43

请记住,如果您选择实现“枚举类”并发现自己处于不允许构造函数为私有的位置,则需要重写 Equals 和 GetHashCode。

Remember that if you choose to go the route of implementing a 'Enum-Class' and find yourself in a position where the constructor isnt allowed to be private, you'll need to override Equals and GetHashCode.

羁客 2024-08-11 03:11:43
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
             };

未测试,但速度很快:)

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
             };

Not tested but was quick :)

说不完的你爱 2024-08-11 03:11:42

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

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

Unfortunately you cannot. Extension methods are a feature which allows you to have the appearance of calling a new method on an instance of a type. It has no capacity to give this capability to types themselves.

When I want to add a set of methods add type level I usually create a new static class called OriginalTypeNameUtil and add the methods there. For example ResponseUtil. This way the class name is visible when I type the original type name.

§对你不离不弃 2024-08-11 03:11:42

我只是做了类似的事情,而不是扩展 Enum 类型,而是扩展了 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));

I'm doing something similar only, instead of extending the Enum type, I extended the 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;

}

and it's called like this:

DataTable tbl = new DataTable().FromEnum(typeof(YourEnum));
jJeQQOZ5 2024-08-11 03:11:42

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

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()
    {
        // ...
    }
}

It seems like you just want a real static method and an "enum-like" class:

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()
    {
        // ...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文