如何使用 C# 关键字作为属性名称? [英] How do I use a C# keyword as a property name?

查看:62
本文介绍了如何使用 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.

这篇关于如何使用 C# 关键字作为属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆