枚举的扩展方法,而不是枚举的实例 [英] Extension method on enumeration, not instance of enumeration
问题描述
public enum Things
{
OneThing ,
AnotherThing
}
我想为此编写一个扩展方法枚举(类似于这里的奖项答案),但是该方法适用于枚举的实例,ala
<$事物东西var list = thing.ToSelectList();
我希望它可以在实际枚举上工作: p>
var list = Things.ToSelectList();
我可以做
var list = default(Things).ToSelectList();
但是我不喜欢那个样子:)
我已经使用以下扩展方法更接近:
public static SelectList ToSelectList(this Type type)
{
if(type.IsEnum)
{
var values =从Enum.GetValues(类型)中的枚举e
选择新的{ID = e,Name = e .ToString()};
返回新的SelectList(值,Id,Name);
}
else
{
返回null;
}
}
像这样使用:
var list = typeof(Things).ToSelectList();
我们可以做得更好吗?
public class SelectList
{
// Normal SelectList properties / methods go here
public static SelectList Of< T>()
{
类型t = typeof(T);
if(t.IsEnum)
{
var values =从Enum.GetValues(类型)中的枚举e
select new {ID = e,Name = e.ToString() };
返回新的SelectList(值,Id,Name);
}
返回null;
}
}
然后你可以得到这样的选择列表: / p>
var list = SelectList.Of< Things>();
IMO读取比 Things.ToSelectList()
。
I have an enumeration for my Things like so:
public enum Things
{
OneThing,
AnotherThing
}
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();
I would like it to work on the actual enumeration instead:
var list = Things.ToSelectList();
I could just do
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;
}
}
Used like so:
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 this reads a lot better than Things.ToSelectList()
.
这篇关于枚举的扩展方法,而不是枚举的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!