代码检查:局部函数可以设为 static
静态局部函数旨在独立于封闭作用域的状态。 因此,如果 ReSharper 检测到一个局部函数未使用封闭作用域中的任何变量,它会建议将该函数设为 static。
通过这种方式,ReSharper 推断出该函数的预期用途,并确保这一意图对将来阅读或修改代码的人清晰可见。
class Test
{
void Foo()
{
Console.WriteLine(LocalFunction1("test "));
// Can be made static because no local variables are captured
string LocalFunction1(string str) => str.Trim(' ');
const string test = "test ";
Console.WriteLine(LocalFunction2());
// Cannot be made static because the variable 'test' is captured
string LocalFunction2() => test.Trim(' ');
}
}
最后修改日期: 2025年 9月 27日