为啥我会收到来自 FxCop 的 InitializeReferenceTypeStaticFieldsInline 警告?
Posted
技术标签:
【中文标题】为啥我会收到来自 FxCop 的 InitializeReferenceTypeStaticFieldsInline 警告?【英文标题】:Why am I getting a InitializeReferenceTypeStaticFieldsInline warning from FxCop?为什么我会收到来自 FxCop 的 InitializeReferenceTypeStaticFieldsInline 警告? 【发布时间】:2015-05-26 21:49:35 【问题描述】:我有这个:
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)
【问题讨论】:
我认为问题不在您发布的代码中。您能否包含一些上下文(特别是突出显示消息所针对的整行代码)?你说你正在初始化一个变量,但没有显示变量的范围或你在哪里初始化它,这就是消息暗示的问题...... @DanPuzey,哎呀。你是对的...... 【参考方案1】:规则的详细信息非常明确。简而言之:在声明它们的位置内联初始化所有静态(共享)变量(就像您对 userName 所做的那样)并摆脱静态构造函数(Shared New),因为它可能会更慢。
【讨论】:
以上是关于为啥我会收到来自 FxCop 的 InitializeReferenceTypeStaticFieldsInline 警告?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我会收到此错误:模块构建失败(来自 ./node_modules/babel-loader/lib/index.js):语法错误 Unexpected token, expected "