C# 的基本语法,标识符,关键字(学习心得 3)

C# 是面对对象的编程。

程序由各种交互对象组成。

同种类对象,通常在相同的 class 中。

例如我们实现一个矩形对象 Rectangle 的类,那这个类下面会有 length 和 width 属性,根据属性计算面积和显示细节。

实例:

using System;
// 任何 C# 程序中第一条都是这个语句
namespace RectangleApplication
    //新建一个命名空间 RectangleApplication
{
    class Rectangle
        //新建一个类
    {
        // 设置变量
        double length;
        double width;
        // 函数-变量赋值
        public void Acceptdetails()
        {
            length = 4.5;
            width = 3.5;
        }
        // 函数-获取面积
        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 ExcuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            // Rectangle 实例化
            r.Acceptdetails();
            // 运行类下面的方法 Acceptdetails 进行赋值
            r.Display();
            // 运行类的方法 Display 进行显示结果
            Console.ReadLine();
            // 这个不知道是做什么用的???
        }
    }
}

运行结果:

Length: 4.5
Width: 3.5
Area: 15.75

标识符

类,变量,函数,或其他项目的名字。

规则如下:

  • 以字母,下划线,@ 开头。
  • 第一个字符不能是数字。
  • 不可包含空格和特殊符号。
  • 不能是 C# 关键字。
  • 大小写敏感。
  • 不能与 C# 类库名称相同。

C# 关键字

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

猜你喜欢

转载自blog.csdn.net/qq_42067550/article/details/106482010