lambda - 避免由于冗余转换而导致 lambda 表达式中出现代码分析 CA1800 错误

标签 lambda refactoring expression code-analysis

背景

我有一个接口(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/

相关文章:

lambda - Church 数字中 m 的 0 次方

r - 在 R 中使用粘贴文本中的上标(对于多个值的向量)

php - 正则表达式中的希伯来语特殊字符

c# - 如何以 Func 类型的表达式作为参数调用方法

java - 如何在 Java 8 中将方法作为参数传递?

包含函数的 java 枚举 - 使用 switch 或 seller 作为成员变量

java - 检查第二个列表中是否缺少第一个列表的任何条目

performance - 哪个更快?比较还是赋值?

java - 重构代码查找二叉树是否是 BST

refactoring - 您能容忍多少重复代码?