简体   繁体   English

解析多个枚举值(已标记):从查询字符串中读取过滤器类型

[英]Parsing multiple enum values (Flagged): Reading in a filter type from a query string

I'm plan to make a page that displays info about user's in the form of a table. 我打算创建一个以表格形式显示用户信息的页面。 Each column will be a property of the table. 每列都是表的属性。 I want someone viewing the table to be able to choose ways to filter the users. 我希望有人在查看表格时能够选择过滤用户的方法。 There will be two check boxes: 1 for reported users and 1 for creation date. 将有两个复选框:1表示报告的用户,1表示创建日期。 I'm planning to make an enum called UserFilter like so: 我打算像这样制作一个名为UserFilter的枚举:

public enum UserFilter
{
   None = 0,
   Date = 1,
   Reported = 2
}

If I need to add another type it's value will be set to 4 so that I can tell which enums are selected through a bitwise or (3 would be both 1 and 2). 如果我需要添加另一个类型,它的值将被设置为4,以便我可以通过按位或(3将是1和2)分辨选择哪些枚举。 The problem I'm having is with reading in an enum from the query string. 我遇到的问题是从查询字符串中读取枚举。 I guess I could do something like posting back with an int (0 for none, 1 for date, 2 for report, 3 for both) but I would like to try posting back with the actual string. 我想我可以做一些事情,比如回复一个int(0表示无,1表示日期,2表示报告,3表示两者)但我想尝试使用实际字符串回发。 I'm not sure how I would parse "Date|Reported" into an enum value that doesn't exist in UserFilter. 我不确定如何将“Date | Reported”解析为UserFilter中不存在的枚举值。

In a nutshell: Is there a clean way to parse "Date|Reported" into the value 3 without adding another value to my enum? 简而言之:是否有一种干净的方法可以将“Date | Reported”解析为值3而不向我的枚举添加其他值?

You could try something like 你可以试试像

string enumString = "Date|Reported";
UserFilter uf = enumString.Split('|').ToList().Select(e =>
{
    UserFilter u;
    Enum.TryParse(e, true, out u);
    return u;
}).Aggregate((u, c) => u = u | c);

I would however recomend that you change your enum to 但是我会建议你将你的枚举改为

public enum UserFilter
{
    None = 1,
    Date = 2,
    Reported = 4
}

as if you have it your way None|Date is the same as Date , because 0 + 1 => 1 好像你有你的方式None|DateDate相同,因为0 + 1 => 1

EDIT 编辑

As @ScottSelby stated, this would also work 正如@ScottSelby所说,这也行得通

UserFilter u = (UserFilter) 3;
//or 6 rather than 3 if you take my comment above into consideration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM