[英]How to use enum as value of the dictionary?
Is there any way to do next, see example: 下一步有什么办法,请参见示例:
I have enum with Filters: 我有过滤器的枚举:
enum SearchFilters
{
Id,
ItemsPerPage
};
enum ReportFilters
{
Name,
Age
};
And enum with pages: 和枚举页面:
enum Pages
{
Search,
Report
};
Is there any way to do something like this: 有什么办法可以做这样的事情:
Dictionary<string, enum> filters = new Dicionary<string, enum>()
{
{Pages.Search.ToString(), SearchFilters},
{Pages.Report.ToString(), ReportFilters}
};
And use it like: 并像这样使用它:
filters[Pages.Search.ToString()]. <--- and here will appear the list of enum values.
For example you can use a value of SearchFilters enum: 例如,您可以使用SearchFilters枚举的值:
filters[Pages.Search.ToString()].ItemPerPage
Any ideas? 有任何想法吗?
Thanks. 谢谢。
You can do something like this. 你可以做这样的事情。 But I don't think the idea of having different enums in the same dictionary is good. 但是我认为在同一词典中具有不同枚举的想法不好。
Dictionary<Pages, Type> filters = new Dictionary<Pages, Type>()
{
{Pages.Search, typeof(SearchFilters)},
{Pages.Report, typeof(ReportFilters)}
};
var arr = Enum.GetValues (filters [Pages.Report]);
You have to either use Dictionary<string, Array>
: 您必须使用Dictionary<string, Array>
:
var filters = new Dictionary<string, Array>()
{
{ "Search", Enum.GetValues(typeof(SearchFilters)) }
};
filters["Search"].Length; // 2.
filters["Search"].Cast<SearchFilters>().Count(); // 2
or just store Type
in Dictionary<string, Type>
: 或仅将Type
存储在Dictionary<string, Type>
:
var filters = new Dictionary<string, Type>()
{
{ "Search", typeof(SearchFilters) }
};
Enum.GetValues(filters["Search"]).Length; // 2
You cannot keep two different types in one dictionary (except you box-unbox the type). 您不能在一个字典中保留两种不同的类型(除非将类型装箱开箱)。 I'd suggest to keep the Key
as enum Page
and value as List<string>
. 我建议将Key
保留为enum Page
,将值保留为List<string>
。
Then you can create following extension for enum: 然后,您可以为枚举创建以下扩展名:
public static List<string> ToMemberList(this Enum enumerationValue)
{
var type = enumerationValue.GetType();
return Enum.GetValues(type).Cast<object>().Select(x => x.ToString()).ToList();
}
And use it this way to create your dictionary: 并以这种方式使用它来创建字典:
var dit = new Dictionary<Pages, List<string>>()
{
{ Pages.Search, SearchFilters.Id.ToMemberList() },
{ Pages.Report, ReportFilters.Age.ToMemberList() }
};
var x1 = dit[Pages.Search];
Here x1 contains list of values in SearchFilters as string. 这里x1包含SearchFilters中的字符串形式的值列表。
Note: Remember to keep the extension method inside a static class. 注意:请记住将扩展方法保留在静态类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.