有条件调用 StartsWith/EndsWith 的最佳方法
我有一个类似于以下的方法:
StringComparison comparison = StringComparison.CurrentCultureIgnoreCase;
switch(SearchType)
{
case SearchType.Contains:
list = list.Where(a => a.Reference.Contains("test",comparison));
break;
case SearchType.StartsWith:
list = list.Where(a => a.Reference.StartsWith("test",comparison));
break;
case SearchType.EndsWith:
list = list.Where(a => a.Reference.EndsWith("test",comparison));
break;
}
您可能会猜到 SearchType 是我的自定义枚举。
有没有更简单的方法来做到这一点,可能使用反射?多个开关看起来有点难看。
I have a method similar to the following:
StringComparison comparison = StringComparison.CurrentCultureIgnoreCase;
switch(SearchType)
{
case SearchType.Contains:
list = list.Where(a => a.Reference.Contains("test",comparison));
break;
case SearchType.StartsWith:
list = list.Where(a => a.Reference.StartsWith("test",comparison));
break;
case SearchType.EndsWith:
list = list.Where(a => a.Reference.EndsWith("test",comparison));
break;
}
As you can probably guess SearchType is a custom enum I have.
Is there an easier way of doing this, possibily using reflection? The multiple switches seem a bit ugly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哪一部分不容易?
我想您可以为每个枚举创建一个类,从通用的 SearchType 接口继承并实现一个名为 ProcessList 的函数 - 不确定哪个列表可以提供更好的功能。
就像......
需要为每个枚举类型做一个类。
然后您需要像这样设置 SearchType 变量...
然后您的开关可以用这个替换...
...在编码方面并不是很容易,但您会得到一个更易读的代码而不是开关。
Which part of that is not easy?
I guess you could have a class for each enum instead, inherit from a common SearchType interface and implement a function called ProcessList - not sure what list is to offer a better function.
Something like..
Need to do a class for each enum type.
Then you would need to set the SearchType variable like this...
and your switch could then be replaced with this...
...Not really easier in terms of coding, but you get a more readable code instead of the switch.
您可以为您的函数提供委托:
You can supply a delegate to your function:
这应该有效:
但是,您真的认为它比标准 switch 语句更具可读性吗?
This should works :
However, do you really think it is more readable than a standard switch statement ?