为什么我从FxCop收到InitializeReferenceTypeStaticFieldsInline警告?

时间:2015-05-26 21:49:36

标签: .net vb.net fxcop

我有这个:

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

1 个答案:

答案 0 :(得分:0)

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