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

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

问题描述

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



  
public枚举响应
{
是= 1,
否= 2,
可能= 3
}



public static DataTable ToDataSource(this Enum e)
{
类型type = e.GetType();
DataTable dt = new DataTable();

dt.Columns.Add(value,typeof(Int32));
dt.Columns.Add(text,typeof(String));

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

return dt;

}


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


$ b $我尝试创建一个新的实例(响应新的响应,response.ToDataSource,但我得到一个构建错误,说它可能不被初始化之前访问。

解决方案

不幸的是,扩展方法是一种功能,可以让你在一个类型的实例上调用一个新的方法,它没有能力给这个类型当我想添加一组方法添加类型级别时,通常会创建一个名为OriginalTypeNameUtil的新的静态类,并在其中添加方法,例如ResponseUtil。当我键入原始类型名称时,类名可见。


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

解决方案

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.

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

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