您的位置:首页 > 编程语言 > C#

C#入门3.2——常量

2016-08-03 18:00 246 查看
常量是指在程序运行中不能改变的数据,定义一个常量与定义一个变量的过程类似,只是多加一个const

定义格式:const 数据类型 常量名称=常量值

说白了就是  const int a=1;

注意:一定要给常量赋值,赋值后不能改变

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
const int banJing = 5;
const double pi = 3.14;
Console.WriteLine("圆的周长是"+2*pi*banJing);
Console.WriteLine("圆的半径是"+pi*banJing*banJing);
Console.ReadKey();
}
}
}

变量、常量、作用域

一般确定作用域有以下规则:

局部变量存在于声明该变量的块语句或方法的大括号内。

在for/while/foreach等循环语句中声明的变量,只作用于该循环体内。

总之,变量作用域为包含它的大括号。

Console.WriteLine(); //输出并换行。

Console.Write(); //仅输出,不换行,

Console.Write("\n"); //通过使用转义字符\n,输出并换行

Console.Write(@"\n"); //这里@的作用就是忽略转义字符\n,屏幕上输出了\n,而不是换行


C#中@符号的作用

1.用 @ 符号加在字符串前面表示其中的转义字符“不”被处理,比如Console.Write(@"\n"); 这里的\n就失去了换行的功能,而作为输出语句被输出。

2.让字符串跨行,有时候一个字符串写在一行中会很长(比如SQL语句),不使用@符号,一种写法是这样的:

string strSQL = "SELECT * FROM HumanResources.Employee AS e"

    + " INNER JOIN Person.Contact AS c"

    + " ON e.ContactID = c.ContactID"

    + " ORDER BY c.LastName";

加上@符号后就可以直接换行了:

string strSQL = @"SELECT * FROM HumanResources.Employee AS e

     INNER JOIN Person.Contact AS c

     ON e.ContactID = c.ContactID

     ORDER BY c.LastName";

3.加上@之后可以使关键字作为标识符,如@int




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: