代码检查:将冗余参数传递给调用方参数表达式参数
[CallerArgumentExpression] 属性在 C# 10 中引入,允许您捕获传递给方法参数的表达式的字符串表示形式。 这对于日志记录、验证或调试目的可能很有用。
如果您使用了由此属性标记的 API,则无需通过另一个参数传递相应参数的字符串表示形式。 因此,JetBrains Rider 将其报告为冗余并建议将其删除。
在下面的示例中,该属性应用于 str 方法的 写入 参数。 这意味着,如果您调用 写入 而未为 str 指定参数,编译器将自动使用为 num 提供的表达式的字符串表示形式。 由于传递给 str 的参数 "a + b" 与传递给 num 的表达式 a + b 的字符串表示形式相匹配,第二个参数变得冗余,可以安全地删除。
using System;
using System.Runtime.CompilerServices;
class RedundantArgument
{
void Write(int num,
[CallerArgumentExpression("num")] string str = "")
=> Console.WriteLine(str);
void Test(int a, int b) => Write(a + b, "a + b");
}
using System;
using System.Runtime.CompilerServices;
class RedundantArgument
{
void Write(int num,
[CallerArgumentExpression("num")] string str = "")
=> Console.WriteLine(str);
void Test(int a, int b) => Write(a + b);
}
最后修改日期: 2025年 9月 26日