如何使用 C# 关键字作为属性名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/421257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a C# keyword as a property name?
提问by Clint Simon
Using asp.net MVC I'd like to do this inside a view:
使用 asp.net MVC 我想在视图中执行此操作:
<%= Html.TextBox("textbox1", null, new { class="class1" }) %>
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 是 C# 中的关键字。我想知道如何转义属性名称以便编译。
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.
如果我将“class”属性更改为“Class”(大写 C),则可以编译它。但这并不合适,因为严格的 xhtml 规定所有属性(和元素)名称必须小写。
采纳答案by Samuel
You can use keywords in C# as identifiers by prepending @ infront of them.
您可以在 C# 中使用关键字作为标识符,方法是在它们前面加上 @。
var @class = new object();
To quote from the MSDN Documentation on C# Keywords:
引用C# 关键字的 MSDN 文档:
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, @ifis a valid identifier but ifis not because if is a keyword.
关键字是预定义的保留标识符,对编译器具有特殊含义。它们不能用作程序中的标识符,除非它们包含@作为前缀。例如,@if是一个有效的标识符,但if不是,因为 if 是一个关键字。