C#基本语法
C# 是一种面向对象的编程语言。在面向对象的程序设计方法中,程序由各种相互交互的对象组成。相同种类的对象通常具有相同的类型,或者说,是在相同的 class 中。
例如,以 Rectangle(矩形)对象为例。它具有 length 和 width 属性。根据设计,它可能需要接受这些属性值、计算面积和显示细节。
让我们来看看一个 Rectangle(矩形)类的实现,并借此讨论 C# 的基本语法:
namespace Test.Test
{
class Rectangle
{
double length = 3;
double width = 2;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length:",length);
Console.WriteLine("Width:", width);
Console.WriteLine("Area:", GetArea());
}
}
class ExecuteRectangle
{
static void Main(String[] args)
{
Rectangle r = new Rectangle();
r.Display();
Console.ReadLine();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
Length: 4.5
Width: 3.5
Area: 15.75
using关键字
- using关键字用于在程序中包含命名空间。一个程序可以包含多个using语句。
class关键字
class关键字用于一个类的声明。
C#中的注释
注释适用于解释代码,编译器会忽略注释的条目。在C#程序中,多以/*开始,并以*/终止。单行注释使用//符号表示。这点和java相同。
多行注释快捷键:ctrl+e+c
取消多行注释快捷键:ctrl+e+u
成员变量、成员方法、实例化对象与java相同
标识符
标识符是用来识别类、变量、函数或任何其他用户定义的项目。在C#中,类的命名必须遵循如下基本规则:
- 标识符必须以字母或下划线(_)开头,后面可以跟一系列的字母、数字或下划线。标识符中的第一个自符不能是数字。
- 标识符必须不包含任何嵌入的空格或符号。
- 标识符不能是C#的关键字
C#关键字
关键字是 C# 编译器预定义的保留字。这些关键字不能用作标识符,但是,如果您想使用这些关键字作为标识符,可以在关键字前面加上 @ 字符作为前缀。
在 C# 中,有些标识符在代码的上下文中有特殊的意义,如 get 和 set,这些被称为上下文关键字(contextual keywords)。
下表列出了 C# 中的保留关键字(Reserved Keywords)和上下文关键字(Contextual Keywords):
abstract | as | base | bool | break | byte | case |
catch | char | checked | class | const | continue | decimal |
default | delegate | do | double | else | enum | event |
explicit | extern | false | finally | fixed | float | for |
foreach | goto | if | implicit | in | in(generic modifier) | int |
interface | internal | is | lock | long | namespace | new |
null | object | operator | out | out(generic modifier) | override | params |
private | protected | public | readonly | ref | return | sbyte |
sealed | short | sizeof | stackalloc | static | string | struct |
switch | this | throw | true | try | typeof | unit |
ulong | unchecked | unsafe | ushort | using | virtual | void |
volatile | while |
add | alias | ascending | descending | dynamic | from | get |
global | group | into | join | let | orderby | partial(type) |
partial(method) | remove | select | set |