Skip to main content
 首页 » 编程设计

c#之Asp.Net MVC 路由在路由中使用 C# 关键字

2024年02月20日14luoye11

我想创建一个使用参数作为 URL 一部分的路由。

我遇到的问题是当我创建默认值时,我不能将参数用作它的保留 C# 字。

想知道是否有办法解决这个问题。 (请参阅在路由中使用参数,当用作默认值时,我得到一个编译器错误:预期的表达式)

示例代码如下:

 routes.MapRoute( 
            name: "Default", 
            url: "{controller}/{action}/{db}/{proc}/{params}", 
            defaults: new { controller = "Data", action = "Index", db = UrlParameter.Optional, proc = UrlParameter.Optional, params = UrlParameter.Optional} 
        ); 

请您参考如下方法:

您可以按照 MSDN 的建议,通过在前面加上 @ 符号来使用 C# 关键字。 在您的情况下,请使用 @params 而不是 params。

To quote 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, @if is a valid identifier but if is not because if is a keyword.

是否有任何特殊原因需要将此变量称为 params?