传递一个查询字符串变量,该变量在c#中是关键字

本文关键字:变量 关键字 字符串 查询 一个 | 更新日期: 2023-09-27 18:06:10

我正在使用一个发布到URL的API。它传递的一个变量叫做event。因为event在c#中是一个关键字,我的代码在它上面挂起了。

public ActionResult Index(string event,string email, string category, string reason, string response, string type, string status)
        {
            return View();
        }

这个问题的解决方法是什么?

传递一个查询字符串变量,该变量在c#中是关键字

关键字通常不能用作参数名。但是,您可以将定义更改为:

public ActionResult Index(string @event, string email, ...) {

出自§2.4.2 c# 4规范的标识符:

前缀"@"允许使用关键字作为标识符,这在与其他编程语言接口时很有用。字符@实际上不是标识符的一部分,因此在其他语言中,标识符可能被视为普通标识符,没有前缀。带有@前缀的标识符称为逐字标识符。对于非关键字的标识符,允许使用@前缀,但出于风格考虑,强烈不建议使用。

这不仅适用于其他语言,也适用于使用c#的反射,这是(我假设)MVC所做的。所以你的方法应该是:

public ActionResult Index(string @event, string email, string category, string reason,
                          string response, string type, string status)
{
    return View();
}