我正在尝试遵循ASP.Net的一些教程,对于我的生活,我只是无法弄清楚@符号在变量之前的作用.
我认为它只是会话变量或request.form的快捷方式,但我在几个地方尝试过它而没有任何运气.
当我随意地把它放在某个地方时,我得到了错误:Expression Expected但是,当我看到我正在使用的例子时,它们看起来不像表达式,所以我很困惑!
请帮忙!?
@C#中的符号允许您使用关键字作为变量名称.
例如:
//this will throw an exception, in C# class is a keyword
string class = "CSS class name";
//this won't
string @class = "CSS class name";
Run Code Online (Sandbox Code Playgroud)
通常最好避免使用关键字作为变量名,但有时它比拥有笨拙的变量名更优雅.在为网络和anon类型序列化内容时,往往会经常看到它们.
您的错误可能是由于@在不是关键字的变量名称之前应用了该错误.
更新:
在T-SQL @中总是在参数名称之前使用,例如:
select *
from [mytable]
where [mytable].[recId] = @id
Run Code Online (Sandbox Code Playgroud)
然后,在调用查询时,请指定@id参数.
@符号有几种不同的用途,具体取决于它的位置.
在变量名称前面,它允许您使用保留字作为变量名称:
string @string = "a string variable named string";
Run Code Online (Sandbox Code Playgroud)
这不是一个好习惯,因为在阅读代码时可能会非常混乱.
在字符串前面,它被称为逐字字符串文字,意味着您不需要转义斜杠等:
string path = @"c:\my path\is here";
string normal_path = "c:\\my path\\is here";
Run Code Online (Sandbox Code Playgroud)
在ASPX页面中,@符号与页面指令一起使用.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Run Code Online (Sandbox Code Playgroud)
在"代码"页面中,@ Symbol用于字符串值转义字符.
String s = @"c:/Document/Files/Sample.txt"
Run Code Online (Sandbox Code Playgroud)