背景
我有一个接口(interface)Interface1,它被Interface2、Interface 3...等继承。除了接口(interface) 1 之外,所有其他接口(interface)都有具体的类(object2、object3...等)来实现各自的接口(interface) Interface 2、Interface 3...等。
我还有一个 Interface 1 类型的对象集合,我的目的是用各种对象填充其中。
问题
我想从此集合中提取特定对象,并为其使用 lambda 表达式。
Object2 = IInterface1Collection.Single(item => item.GetType()==typeof(Object2)
&& ((Object2)item).Property1=="John" && ((Object2)item).Property2==0);
此代码给出了 CA1800 的代码分析性能错误。它说
Error 1 CA1800 : Microsoft.Performance : 'item', a parameter, is cast to type 'Object2' multiple times in method 'Method1()'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.
如果我抑制该消息,它会正常工作并让我获得满足条件的 Object2。
问题
如何避免出现此错误消息?我必须将 item 转换为 Object2,否则我无法访问其属性。我无法承担创建 Object2 集合的费用。
最佳答案
我建议首先使用OfType
:
Object2 = IInterface1Collection.OfType<Object2>()
.Single(item => item.Property1 == "John" &&
item.Property2 == 0);
请注意,其行为略有不同,因为它还包含Object2
的子类实例。那是问题吗?如果是这样,您可以随时编写:
Object2 = IInterface1Collection.OfType<Object2>()
.Single(item => item.GetType() == typeof(Object2))
item.Property1 == "John" &&
item.Property2 == 0);
关于lambda - 避免由于冗余转换而导致 lambda 表达式中出现代码分析 CA1800 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860337/