是否建议转义关键字,例如 @class
在 C# 中,您可以使用 @languagekeyword
创建与关键字同名的变量。
我的问题是,这什么时候有用?什么时候好处会超过坏处?
In c# you can create variables named identically to a keyword by using @languagekeyword
.
My question is, when would this be useful? When would the benefits out-weigh the drawbacks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
CLR 可以作为许多不同编程语言的目标。一种语言的标识符是另一种语言的关键字。如果用一种语言编写的类库不能从另一种语言中使用,那将很糟糕,因为声明的方法或属性的名称是该语言中的关键字。
The CLR can be targeted by many different programming languages. One language's identifier is another language's keyword. It would be bad if a class library written in one language couldn't be used from another language because a declared method or property has a name that is a keyword in that language.
使用这些语法的一个简单示例是在 Web 应用程序中,您可能需要通过提供类似这样的对象来为 HTML 标记设置一些属性,
如果没有该语法,这是不可能的。
A simple example for a use of these syntax would be in a web application where you may be required to set some attributes to an HTML tag by giving an object like
This would not be possible without that syntax.
如果您正在编写代码生成框架并且您的底层模型(例如数据库)可能包含使用关键字的域对象(例如数据库表或名为“事件”的字段),那么它是最有用的。在这种情况下,您可以转义所有名称,并且不会发生冲突。如果添加新关键字,这使得代码生成器向前兼容。
It is most useful if you are writing a code generation framework and your underlying model (e.g. a DB) may contain domain objects that use keywords e.g. a db table or field named "event". In this case you can escape all names and there will be no clashes. This makes a code generator forward compatible if new keywords are added.
一般来说:
当你选择自己的名字时,尽量避免使用它。
然而,有时你不能完全选择自己的名字。例如,当您移植代码时,或者当您为用另一种语言编写的代码编写包装器时。在这种情况下,我认为最好坚持使用原始名称,以便 API 描述仍然与您的代码匹配,而不是仅仅为了避免与保留关键字冲突而考虑新名称。
In general:
When you pick your own names, try to avoid it.
However, sometimes you don't entirely get to pick your own names. For example when you port code, or when you write a wrapper around code that's written in another language. In such cases I think it's better to stick to the original names, so that API descriptions still match with your code, instead of thinking of new names just to avoid a clash with reserved keywords.
不建议使用与保留关键字冲突的变量名,但有时为了可读性您可能不希望遵循该规则。
例如:
它有点突出了代码的重要部分。
当您需要使用无法更改的第三方代码时,会想到其他情况。
It is not advisable to use variable names that conflict with reserved keyword but sometimes you may want to not follow that rule for readability.
For example:
It kinda highlights the important part of code.
Other cases come to mind when you need to use third party code that you cannot change.