2015-04-21 29 views
1

我有以下幾點:爲什麼FxCop給我一個「DoNotCastUnnecessarily」警告?

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) 
} 

我在做什麼錯?我檢查類型,如果它是相同的,則投射。

回答

6

因爲你可以重寫你投以

Dim rt As String = TryCast(obj, Root) 
If Not (rt is Nohting) Then 

這比is組合和更高性能的DirectCast

3

正在使用的語言似乎是針對C#,但它基本上是要求你使用TryCast代替Is

Dim rt As Root = TryCast(obj, Root) 
    If Not (rt Is Nothing) Then 
     ' code 
    End If 

的原因是,這個內部PE無論如何,它們相當於TryCast,所以努力是重複的。

相關問題