在列举的扩展方法,而不是列举实例 [英] Extension method on enumeration, not instance of enumeration
问题描述
我有我的东西的枚举,像这样:
I have an enumeration for my Things like so:
public enum Things
{
OneThing,
AnotherThing
}
我想为这个枚举一个扩展方法(类似于<一个href=\"http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc/694361#694361\">Prise's回答这里),但而工作方法上的枚举的实例的,阿拉
I would like to write an extension method for this enumeration (similar to Prise's answer here) but while that method works on an instance of the enumeration, ala
Things thing; var list = thing.ToSelectList();
我想它在的实际统计工作的代替:
var list = Things.ToSelectList();
我只是做
var list = default(Things).ToSelectList();
但我不喜欢的是,看看:)
But I don't like the look of that :)
我已经得到了具有以下扩展方法接近:
I have gotten closer with the following extension method:
public static SelectList ToSelectList(this Type type)
{
if (type.IsEnum)
{
var values = from Enum e in Enum.GetValues(type)
select new { ID = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name");
}
else
{
return null;
}
}
用于像这样:
var list = typeof(Things).ToSelectList();
我们可以做任何比这更好的?
Can we do any better than that?
推荐答案
扩展方法只对实例的工作,所以它不能这样做,但也有一些精心挑选的类/方法的名称和仿制药,就可以产生一个结果看起来一样好:
Extension methods only work on instances, so it can't be done, but with some well-chosen class/method names and generics, you can produce a result that looks just as good:
public class SelectList
{
// Normal SelectList properties/methods go here
public static SelectList Of<T>()
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(type)
select new { ID = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name");
}
return null;
}
}
然后你就可以得到你的选择列表如下:
Then you can get your select list like this:
var list = SelectList.Of<Things>();
这IMO比读 Things.ToSelectList()
。
这篇关于在列举的扩展方法,而不是列举实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!