C# 中的条件简写类似于 SQL“in” 关键词
在 C# 中是否有一种简写方法可以这样写:
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
比如:
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
我知道我也可以使用 switch,但是我必须编写大约 50 个这样的函数(将经典 ASP 站点移植到 ASP.NET),所以我'我想让它们尽可能短。
In C# is there a shorthand way to write this:
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
Like:
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这个怎么样?
用法:
我不能声称对此有功劳,但我也不记得我在哪里看到过它。 所以,感谢你,匿名的互联网陌生人。
How about this?
Usage:
I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.
这样的事情怎么样:(
当然,您可以根据您的需要更改静态状态,在其他地方初始化 IDs 类,使用 IEnumerable<> 等。要点是最接近的等价于 < SQL 中的 em>in 运算符是 Collection.Contains() 函数。)
How about something like this:
(You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable<>, etc, based on your needs. The main point is that the closest equivalent to the in operator in SQL is the Collection.Contains() function.)
一个不错的小技巧是反转您通常使用 .Contains() 的方式,例如:-
您可以在数组中放置任意数量的条目。
如果 Personnel.x 是一个枚举,您会遇到一些转换问题(以及您发布的原始代码),在这种情况下,它会更容易使用:-
A nice little trick is to sort of reverse the way you usually use .Contains(), like:-
Where you can put as many entries in the array as you like.
If the Personnel.x is an enum you'd have some casting issues with this (and with the original code you posted), and in that case it'd be easier to use:-
这是我能想到的最接近的:
Here's the closest that I can think of:
你能为人员编写一个迭代器吗?
Can you write an iterator for Personnel.
只是另一个语法想法:
Just another syntax idea:
我会将允许的 ID 列表封装为数据而不是代码。 这样以后就可以轻松更改其来源。
如果使用 .NET 3.5,由于扩展方法,您可以使用
IEnumerable
而不是List
。(此函数不应该是静态的。请参阅此帖子:使用太多静电是好是坏?。)
I would encapsulate the list of allowed IDs as data not code. Then it's source can be changed easily later on.
If using .NET 3.5, you can use
IEnumerable
instead ofList
thanks to extension methods.(This function shouldn't be static. See this posting: using too much static bad or good ?.)
权限是否基于用户 ID? 如果是这样,您可能会通过基于角色的权限获得更好的解决方案。 或者您最终可能不得不频繁地编辑该方法以将其他用户添加到“允许的用户”列表中。
例如,
枚举用户角色{
用户、管理员、皇帝
}
Are permissions user-id based? If so, you may end up with a better solution by going to role based permissions. Or you may end up having to edit that method quite frequently to add additional users to the "allowed users" list.
For example,
enum UserRole {
User, Administrator, LordEmperor
}