C# 是面向对象的编程语言。在面向对象编程方法中,程序由通过动作相互交互的各种对象组成。 对象可能采取的操作称为方法。具有相同类型的对象认为是相同的类型,或者说是在同一个类。
例如,假设有一个Rectangle
对象。 它有长度(length
)和宽度(width
)的属性。 根据设计,它可能需要接受这些属性的值,计算面积和显示细节的方法。
下面我们来看看Rectangle
类是如何实现上述功能,并以此学习 C# 的基本语法:
using System
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length
double width
public void Acceptdetails()
{
length = 10.0
width = 20.1
}
public double GetArea()
{
return length * width
}
public void Display()
{
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
}
}
}
当编译和执行上述代码时,会产生以下结果:
Length: 10.0
Width: 20.1
Area: 201
using关键字
任何 C# 程序中的第一个语句一般是:
using System
using
关键字用于在程序中包含命名空间。程序可以包括多个using
语句。
class关键字
class
关键字用于声明一个类。
C# 中的注释
注释用于解释代码。编译器忽略注释中的任何内容。 C# 程序中的多行注释以/*
开始,并以*/
结尾,如下所示:
/* This program demonstrates
The basic syntax of C# programming
Language */
单行注释由“//”
符号表示。 例如,
}//end class Rectangle
// 另一个行注释
成员变量
变量是用于存储类的属性或数据成员的数据。在前面的程序中,Rectangle
类有两个名为length
和width
的成员变量。
成员函数
函数是执行特定任务的语句集合。类的成员函数在类中声明。我们的示例类Rectangle
包含三个成员函数:AcceptDetails
,GetArea和Display
。
实例化类
在上述程序中,ExecuteRectangle
类包含Main()
方法,并实例化了一个Rectangle
类的实例:r
。
标识符
标识符是用于标识类,变量,函数或任何其他用户定义项目的名称。 C# 中命名类的基本规则如下:
- 名称必须以字母开头,后面可以有一系列字母,数字(
0 - 9
)或下划线(_
)。 标识符中的第一个字符不能为数字。 - 它不能包含任何嵌入的空格或符号,如:
?
,-
,+
,!
,@
,#
,%
,^
,&
,*
,(
,)
,[
,]
,{
,}
,.
,,
:
,"
,&apos
,/
和\
。但是,可以使用下划线(_
)。 - 它不能是 C# 关键字。
C# 关键字
关键字是预定义为 C# 编译器的保留字。 这些关键字不能用作标识符。 但是,如果要使用这些关键字作为标识符,但可以使用@
字符将关键字前缀来表示某一标识符。
在 C# 中,一些标识符在代码的上下文中具有特殊意义,例如get
和set
被称为上下文关键字。
下表列出了 C# 中的保留关键字和上下文关键字:
保留关键字
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 | uint |
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 | - | - | - |