如何使用 C# 关键字作为属性名称?
使用 asp.net MVC 我想在视图中执行此操作:
Using asp.net MVC I'd like to do this inside a view:
<%= Html.TextBox("textbox1", null, new { class="class1" }) %>
此语句无法编译,因为 class 是 C# 中的关键字.我想知道如何转义属性名称以便编译.
This statement does not compile because class is keyword in C#. I'd like to know how I can escape the property names such that this compiles.
如果我将class"属性更改为Class"(大写 C),则可以编译它.但这并不合适,因为严格的 xhtml 规定所有属性(和元素)名称必须小写.
It is possible to get this to compile if I change the "class" property to "Class" (uppercase C). But this is not suitable because strict xhtml says that all attributes (and element) names must be lowercase.
您可以在 C# 中使用关键字作为标识符,方法是在关键字前面加上 @.
You can use keywords in C# as identifiers by prepending @ infront of them.
var @class = new object();
引用关于 C# 关键字的 MSDN 文档:
To quote from the MSDN Documentation on C# Keywords:
关键字是预定义的保留标识符,具有特殊的对编译器的意义.它们不能用作您的标识符除非它们包含 @ 作为前缀.例如,@if 是一个有效的标识符但 if 不是因为 if 是关键字.
Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.