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
任何 c# 程序中的第一个语句一般是:
using system;
using关键字用于在程序中包含命名空间。程序可以包括多个using语句。
class关键字用于声明一个类。
注释用于解释代码。编译器忽略注释中的任何内容。 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)或下划线(_)。 标识符中的第一个字符不能为数字。?, -, +, !,@,#, %, ^, &, *, (, ), [, ], {, }, ., ;, :, ", ',/ 和\。但是,可以使用下划线(_)。关键字是预定义为 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 | - | - | - |