为什么 FxCop 给我一个 "DoNotCastUnnecessarily" 警告?
Why is FxCop giving me a "DoNotCastUnnecessarily" warning?
我有以下内容:
Option Strict On
Public NotInheritable Class Root
Public Overrides Function Equals(obj As Object) As Boolean
If TypeOf obj Is Root Then
Dim rt As Root = DirectCast(obj, Root)
Return rt.container.Equals(Me.container) AndAlso
rt.question.Equals(Me.question)
End If
Return False
End Function
End Class
FxCop 给我这个警告:
Warning, Certainty 95, for DoNotCastUnnecessarily
{
Target : #Equals(System.Object) (IntrospectionTargetMember)
Location : file:///C:/..../Root.vb<46> (String)
Resolution : "'obj', a parameter, is cast to type 'Root' multiple
times in method 'Root.Equals(Object)'. Cache the result
of the 'as' operator or direct cast in order to eliminate
the redundant castclass instruction."
Help : http://msdn2.microsoft.com/library/ms182271(VS.90).aspx (String)
Category : Microsoft.Performance (String)
CheckId : CA1800 (String)
RuleFile : Performance Rules (String)
Info : "Avoid duplicate casts where possible, since there is
a cost associated with them."
Created : 4/21/2015 8:45:17 PM (DateTime)
LastSeen : 4/21/2015 8:55:16 PM (DateTime)
Status : Active (MessageStatus)
Fix Category : NonBreaking (FixCategories)
}
我做错了什么?我检查类型,如果相同则进行转换。
因为您可以将演员表重写为
Dim rt As String = TryCast(obj, Root)
If Not (rt is Nohting) Then
这比 is
和 DirectCast
的组合更高效
正在使用的语言似乎是为 C# 量身定制的,但它基本上要求您使用 TryCast
而不是 Is
Dim rt As Root = TryCast(obj, Root)
If Not (rt Is Nothing) Then
' code
End If
原因是无论如何这在内部执行等同于 TryCast
,所以工作是重复的。
我有以下内容:
Option Strict On
Public NotInheritable Class Root
Public Overrides Function Equals(obj As Object) As Boolean
If TypeOf obj Is Root Then
Dim rt As Root = DirectCast(obj, Root)
Return rt.container.Equals(Me.container) AndAlso
rt.question.Equals(Me.question)
End If
Return False
End Function
End Class
FxCop 给我这个警告:
Warning, Certainty 95, for DoNotCastUnnecessarily
{
Target : #Equals(System.Object) (IntrospectionTargetMember)
Location : file:///C:/..../Root.vb<46> (String)
Resolution : "'obj', a parameter, is cast to type 'Root' multiple
times in method 'Root.Equals(Object)'. Cache the result
of the 'as' operator or direct cast in order to eliminate
the redundant castclass instruction."
Help : http://msdn2.microsoft.com/library/ms182271(VS.90).aspx (String)
Category : Microsoft.Performance (String)
CheckId : CA1800 (String)
RuleFile : Performance Rules (String)
Info : "Avoid duplicate casts where possible, since there is
a cost associated with them."
Created : 4/21/2015 8:45:17 PM (DateTime)
LastSeen : 4/21/2015 8:55:16 PM (DateTime)
Status : Active (MessageStatus)
Fix Category : NonBreaking (FixCategories)
}
我做错了什么?我检查类型,如果相同则进行转换。
因为您可以将演员表重写为
Dim rt As String = TryCast(obj, Root)
If Not (rt is Nohting) Then
这比 is
和 DirectCast
正在使用的语言似乎是为 C# 量身定制的,但它基本上要求您使用 TryCast
而不是 Is
Dim rt As Root = TryCast(obj, Root)
If Not (rt Is Nothing) Then
' code
End If
原因是无论如何这在内部执行等同于 TryCast
,所以工作是重复的。