2015-05-26 91 views
0

我有这样的:为什么我从FxCop获得InitializeReferenceTypeStaticFieldsInline警告?

Public Class Foo 
    Private Shared ReadOnly machineName As String 
    Private Shared ReadOnly userName As String = Environment.UserName 
    Private Shared ReadOnly domainName As String 
    Private Shared ReadOnly events As New List(Of ManualResetEvent)() 

    Shared Sub New() 

     AddHandler AppDomain.CurrentDomain.ProcessExit, 
      New EventHandler(AddressOf Wait) 
     'wait for all tasks to complete before the process terminates 

     Try 
      machineName = Environment.MachineName 
     Catch ex As InvalidOperationException 
      machineName = "" 
     End Try 

     Try 
      domainName = Environment.UserDomainName 
     Catch ex As InvalidOperationException 
      domainName = "" 
     Catch ex As PlatformNotSupportedException 
      domainName = "" 
     End Try 

    End Sub 
End Class 

什么的FxCop告诉我在这里做什么?

CriticalWarning, Certainty 90, for InitializeReferenceTypeStaticFieldsInline 
{ 
    Target  : #.cctor() (IntrospectionTargetMember) 
    Location  : file://blah/blah/blah 
    Resolution : "Initialize all static fields in 'Namespace' 
        when those fields are declared and remove the explicit 
        static constructor." 
    Help   : http://msdn2.microsoft.com/library/ms182275(VS.90).aspx (String) 
    Category  : Microsoft.Performance (String) 
    CheckId  : CA1810 (String) 
    RuleFile  : Performance Rules (String) 
    Info   : "Static fields should be initialized when declared. 
        Initializing static data in explicit static constructors 
        results in less performant code." 
    Created  : 5/26/2015 9:46:09 PM (DateTime) 
    LastSeen  : 5/26/2015 9:46:09 PM (DateTime) 
    Status  : Active (MessageStatus) 
    Fix Category : NonBreaking (FixCategories) 
} 
+0

我认为问题不在您发布的代码中。你能否包含一些上下文(特别是突出显示消息所提供的全部代码)?你说你正在初始化一个变量,但没有显示变量的范围或你正在初始化它的位置,这就是消息暗示的问题... –

+0

@DanPuzey,哎呀。你是对的.... –

回答

0

该规则的详细消息非常明确。简而言之:初始化你声明的所有静态(共享)变量的内联位置(就像你对userName所做的那样)并且摆脱静态构造函数(Shared New),因为它可能会变慢。

相关问题