c# - 代码分析 c# .NET CA1822

标签 c# static code-analysis

我运行代码分析并收到此消息:

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 建议我将其标记为静态。

我的问题:

  1. 为什么当我将其标记为静态时,性能会提高?
  2. 我的函数是库的一部分,应该是线程安全的,将方法标记为静态会阻止这种情况吗?
  3. 我有额外的私有(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/

相关文章:

c# - 非标准时区字符串的 DateTime.ParseExact 问题

c# - 15000 个到 sql server 2008 的连接处于 “sleeping” 状态

java - java中最终字段的多个构造函数

iphone - xcodebuild 生成空的compile_commands.json

code-analysis - 警告未使用的 using 语句的静态分析规则是什么?

c# - 获取驱动器列表,包括共享 RDP 驱动器

c++ - 非静态成员变量创建类似于 C++ 中的静态单例创建

c# - 静态终结器

c - 在 C 中生成跨多个文件的现有函数列表

c# - 在 Xamarin.Android 上以编程方式绘制 DrawableLeft?