枚举扩展方法 - ToDataSource [英] Enum Extension Method – ToDataSource

查看:131
本文介绍了枚举扩展方法 - ToDataSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

}


然而有,我可以使用枚举本身(Response.ToDataSource)扩展方法,而不是用它挂值Responce.Yes.ToDataSource的一种方式?

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 creating an new instance (Response new response, response.ToDataSource but I get a build error saying that "it may not be initialised before accessing".

推荐答案

不幸的是你不能。扩展方法是一个功能,它可以让你有调用一个类型的实例的新方法的出现。它没有能力给这个能力类型自身。

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.

当我想补充的一套方法添加式液位我通常创建一个名为OriginalTypeNameUtil一个新的静态类,并添加方法那里。例如ResponseUtil。当我输入原始类型名这样的类名是可见的。

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.

这篇关于枚举扩展方法 - ToDataSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆