我运行代码分析并收到此消息:
CA1822 : Microsoft.Performance : The 'this' parameter (or 'Me' in Visual Basic) of 'CreateIntervalString(TimeSpan)' is never used. Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body or at least one property accessor, if appropriate.
我的代码是:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
据我了解,因为 CreateIntervalString
函数不使用类的任何成员,并且仅在 timeSpan 输入上使用,VisualStudio 建议我将其标记为静态。
我的问题:
- 为什么当我将其标记为静态时,性能会提高?
- 我的函数是库的一部分,应该是线程安全的,将方法标记为静态会阻止这种情况吗?
- 我有额外的私有(private)函数,它们只使用它的输入,不使用类的任何其他成员,但我没有为它们得到同样的错误。
非常感谢!
例子:
以下方法会报错:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
并且以下不会:
private DateTime ParseDateString(string dateTimeString)
{
// the years,monthe,days,hours,minutes and secondes found by the dateTimeString input
return new DateTime(years, months, days, hours, minutes, secondes);
}
最佳答案
MSDN 站点 http://msdn.microsoft.com/en-us/library/ms245046.aspx给出性能方面的答案
如果该方法未标记为静态,则运行时将检查当前对象 (this) 是否为 null。在大多数情况下,几乎没有可观察到的差异,这是事实,但如果每秒调用数百万次的方法可以通过静态化获得这种 yield ,那么它可能是值得的。
关于c# - 代码分析 c# .NET CA1822,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6483720/