[英]Reflection bool property in LINQ
I want to use reflection to write this code better. 我想用反射来更好地编写这段代码。 I now have the IsSearchable
and IsEditable
functions, but can I refactor this code to get the part c.Searchable and c.Editable out? 我现在有IsSearchable
和IsEditable
函数,但是我可以重构这个代码来获取c .Searchable和c.Editable吗?
I have 10 functions like this and only need one. 我有10个这样的功能,只需要一个。 The only different part is what bool property to check, c.Searchable
or c.Editable
. 唯一不同的部分是要检查的bool属性, c.Editable
。可c.Searchable
或c.Editable
。
bool searchable = conditions
.Select(c => c.Searchable)
.SingleOrDefault();
bool editable = conditions
.Select(c => c.Editable)
.SingleOrDefault();
Using reflection is overkill. 使用反射是过度的。 Assuming you are checking to see if there are ANY conditions in the list that match Editable
or Searchable
, you should maybe just use the Any()
syntax... 假设您正在检查列表中是否存在与Editable
或Searchable
匹配的任何条件,您应该只使用Any()
语法...
You could use a method such as 你可以使用像
public bool CheckCondition(IEnumerable<Condition> conditions, Func<Condition, bool> predicate)
{
return conditions.Any(predicate);
}
and use it like: 并使用它像:
var isSet = CheckCondition(conditions, c => c.Editable);
But you aren't saving yourself much. 但是你并没有为自己节省太多。 You might as well just write the Any()
every time. 你不妨每次都写下Any()
。 For example, 例如,
var isEditable = conditions.Any(c => c.Editable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.