当抛出带有 @Escaped 标识符的 ArgumentException 时,我应该使用什么作为 paramName?
When throwing an ArgumentException with an @Escaped identifier, what should I use as the paramName?
当抛出带有@Escaped 标识符的ArgumentException (EG @this
) 时,我应该使用什么作为paramName?我会使用 this
还是 @this
?
举个例子,假设我有一个枚举 SomeEnum
的扩展方法。当此处存在无效枚举时,我想抛出一个 InvalidEnumArgumentException
。
public static string GetCode(this SomeEnum @this) {
switch (@this) {
case SomeEnum.Foo: return "Foo";
case SomeEnum.Bar: return "Bar";
case SomeEnum.Baz: return "Baz";
//This is what I'm not sure of vvvvv
default: throw new InvalidEnumArgumentException("@this", (int)@this, typeof(SomeEnum));
}
}
以上是正确的方法吗?或者我应该这样做:
default: throw new InvalidEnumArgumentException("this", (int)@this, typeof(SomeEnum));
鉴于不同的语言对此有不同的语法(据我所知VB使用[this]
),我认为第二个选项是正确的,但我想验证一下.
编辑:澄清一下,因为大多数人似乎不知道:当标识符以 @
开头时,它被迫被视为标识符而不是关键字,但是 @something
和 something
仍然是相同的标识符。 Source。当然,这在执行 @this
时不适用,因为 this
不是有效标识符。
首先避免使用关键字通常是更好的解决方案:
public static string GetCode(this SomeEnum aSomeEnum)
{
switch (aSomeEnum)
{
case SomeEnum.Foo: return "Foo";
case SomeEnum.Bar: return "Bar";
case SomeEnum.Baz: return "Baz";
default: throw new InvalidEnumArgumentException("aSomeEnum", (int)aSomeEnum, typeof(SomeEnum));
}
}
正如其他人所指出的,"this" 是参数名称的错误选择——它会导致不必要的混淆。选择其他任何东西(我会选择 someEnum
)。如果您 do 将参数命名为 "this",那么您应该在构造函数中使用它,因为这就是它的名称。您必须如何转义该名称以使 C# 接受它与其运行时名称无关,如果您想成为一个优秀的、与语言无关的 .NET 公民,这就是异常应该关注的问题。 (但是,恰好 因为 this
对 C# 程序员来说太熟悉了。)
参数的实际名称(虽然很可怕)是 "this"
。这就是您将在元数据中看到的内容。 @
只是必需的,以便编译器知道您实际上是故意使用保留字 。
当抛出带有@Escaped 标识符的ArgumentException (EG @this
) 时,我应该使用什么作为paramName?我会使用 this
还是 @this
?
举个例子,假设我有一个枚举 SomeEnum
的扩展方法。当此处存在无效枚举时,我想抛出一个 InvalidEnumArgumentException
。
public static string GetCode(this SomeEnum @this) {
switch (@this) {
case SomeEnum.Foo: return "Foo";
case SomeEnum.Bar: return "Bar";
case SomeEnum.Baz: return "Baz";
//This is what I'm not sure of vvvvv
default: throw new InvalidEnumArgumentException("@this", (int)@this, typeof(SomeEnum));
}
}
以上是正确的方法吗?或者我应该这样做:
default: throw new InvalidEnumArgumentException("this", (int)@this, typeof(SomeEnum));
鉴于不同的语言对此有不同的语法(据我所知VB使用[this]
),我认为第二个选项是正确的,但我想验证一下.
编辑:澄清一下,因为大多数人似乎不知道:当标识符以 @
开头时,它被迫被视为标识符而不是关键字,但是 @something
和 something
仍然是相同的标识符。 Source。当然,这在执行 @this
时不适用,因为 this
不是有效标识符。
首先避免使用关键字通常是更好的解决方案:
public static string GetCode(this SomeEnum aSomeEnum)
{
switch (aSomeEnum)
{
case SomeEnum.Foo: return "Foo";
case SomeEnum.Bar: return "Bar";
case SomeEnum.Baz: return "Baz";
default: throw new InvalidEnumArgumentException("aSomeEnum", (int)aSomeEnum, typeof(SomeEnum));
}
}
正如其他人所指出的,"this" 是参数名称的错误选择——它会导致不必要的混淆。选择其他任何东西(我会选择 someEnum
)。如果您 do 将参数命名为 "this",那么您应该在构造函数中使用它,因为这就是它的名称。您必须如何转义该名称以使 C# 接受它与其运行时名称无关,如果您想成为一个优秀的、与语言无关的 .NET 公民,这就是异常应该关注的问题。 (但是,恰好 因为 this
对 C# 程序员来说太熟悉了。)
参数的实际名称(虽然很可怕)是 "this"
。这就是您将在元数据中看到的内容。 @
只是必需的,以便编译器知道您实际上是故意使用保留字 。