第三章:C# 程序结构

本文详细介绍了C#程序的基本结构,包括命名空间、类、方法、变量和语句。通过实例解析了这些概念,帮助读者理解C#编程的基础,并提供了练习题加深理解。

在开始编写复杂的C#程序之前,首先需要了解C#程序的基本结构。一个C#程序由多个部分组成,包括命名空间、类、方法、变量和语句等。掌握这些基础概念将有助于你编写清晰、结构化和易于维护的代码。

1. 命名空间(Namespace)

命名空间用于组织代码,将相关的类、结构、接口和枚举等类型归类在一起,以避免命名冲突。命名空间通常与项目的目录结构对应。

示例:

using System;

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

在上面的示例中,MyApplication是命名空间,包含一个Program类。using System;语句用于导入System命名空间,其中包含常用的基础类库,如Console类。

2. 类(Class)

类是面向对象编程的基本构建块。它是一个模板,用于创建对象。类定义了对象的属性(字段)和行为(方法)。

示例:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Name = "John";
            person.SayHello();
        }
    }

    class Person
    {
        public string Name { get; set; }

        public void SayHello()
        {
            Console.WriteLine($"Hello, my name is {Name}.");
        }
    }
}

在这个示例中,我们定义了一个Person类,其中包含一个Name属性和一个SayHello方法。在Main方法中,我们创建了一个Person对象,并调用其方法。

3. 方法(Method)

方法是定义在类中的函数,用于执行特定的任务。每个C#程序的入口点都是一个Main方法,它是一个特殊的方法,必须定义在一个类中,并且必须是static的。

示例:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            GreetUser("Alice");
        }

        static void GreetUser(string name)
        {
            Console.WriteLine($"Hello, {name}!");
        }
    }
}

在这个示例中,我们定义了一个名为GreetUser的方法,它接受一个字符串参数,并输出一条问候消息。在Main方法中,我们调用了GreetUser方法并传递了一个字符串参数。

4. 变量(Variables)

变量是存储数据的命名位置。C# 是一种强类型语言,变量必须先声明其类型然后才能使用。

示例:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            double pi = 3.14;
            string greeting = "Hello, World!";
            bool isCSharpFun = true;

            Console.WriteLine(number);
            Console.WriteLine(pi);
            Console.WriteLine(greeting);
            Console.WriteLine(isCSharpFun);
        }
    }
}

在这个示例中,我们声明并初始化了四个变量,分别是整数、双精度浮点数、字符串和布尔值,并在控制台输出它们的值。

5. 语句(Statements)

语句是C#程序的基本执行单元,用于描述程序的逻辑。C# 支持多种类型的语句,如表达式语句、声明语句、选择语句、循环语句等。

示例:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 5;

            // if-else 语句
            if (number > 0)
            {
                Console.WriteLine("The number is positive.");
            }
            else
            {
                Console.WriteLine("The number is not positive.");
            }

            // while 循环
            int count = 0;
            while (count < 5)
            {
                Console.WriteLine(count);
                count++;
            }

            // for 循环
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(i);
            }

            // switch 语句
            switch (number)
            {
                case 1:
                    Console.WriteLine("One");
                    break;
                case 2:
                    Console.WriteLine("Two");
                    break;
                default:
                    Console.WriteLine("Other number");
                    break;
            }
        }
    }
}

在这个示例中,我们展示了几种常见的语句类型,包括if-else条件语句、while循环、for循环和switch语句。

6. C# 程序的基本结构

一个典型的C#程序通常包括以下部分:

  1. 命名空间声明:定义程序使用的命名空间。
  2. 类声明:定义一个或多个类,每个类包含属性和方法。
  3. Main方法:程序的入口点,定义程序的主要逻辑。
  4. 语句和表达式:在方法中使用语句和表达式描述程序的具体行为。

综合示例:

using System;

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.Make = "Toyota";
            myCar.Model = "Corolla";
            myCar.Year = 2020;

            Console.WriteLine($"Car: {myCar.Make} {myCar.Model} ({myCar.Year})");
            myCar.Start();
        }
    }

    class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }

        public void Start()
        {
            Console.WriteLine("The car has started.");
        }
    }
}

在这个综合示例中,我们定义了一个Car类,包含三个属性和一个方法。在Main方法中,我们创建了一个Car对象,设置其属性并调用其方法。

结束语

待补充。

练习与思考

练习 1:命名空间和类

问题: 创建一个名为Library的命名空间,在其中定义一个Book类。Book类应包含以下属性:Title(字符串类型)、Author(字符串类型)和Pages(整数类型)。在Main方法中,创建一个Book对象,并设置其属性值,然后输出这些属性值。

答案:

using System;

namespace Library
{
    class Program
    {
        static void Main(string[] args)
        {
            Book myBook = new Book();
            myBook.Title = "To Kill a Mockingbird";
            myBook.Author = "Harper Lee";
            myBook.Pages = 281;

            Console.WriteLine($"Title: {myBook.Title}");
            Console.WriteLine($"Author: {myBook.Author}");
            Console.WriteLine($"Pages: {myBook.Pages}");
        }
    }

    class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public int Pages { get; set; }
    }
}

上述代码定义了一个新的命名空间Library,并在其中创建了一个包含属性的Book类。通过创建Book对象并设置其属性,熟悉类和对象的基本操作。

练习 2:方法和变量

问题:Program类中定义一个名为Add的方法,该方法接受两个整数参数,并返回它们的和。在Main方法中,调用Add方法,并输出其返回值。

答案:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = Add(5, 7);
            Console.WriteLine($"The sum is: {result}");
        }

        static int Add(int a, int b)
        {
            return a + b;
        }
    }
}

通过这个练习,练习方法的定义和调用,以及如何处理方法的返回值。熟悉如何传递参数和使用变量来存储和输出结果。

练习 3:语句和循环

问题: 编写一个程序,使用for循环从1到10输出所有偶数。在Main方法中实现该功能。

答案:

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
            {
                if (i % 2 == 0)
                {
                    Console.WriteLine(i);
                }
            }
        }
    }
}

通过这个练习熟悉for循环和条件语句的结合使用。学习如何使用循环来遍历一系列数值,并使用条件语句筛选出特定的值。

练习 4:综合练习

问题: 创建一个名为Animal的类,包含属性NameSound,以及一个方法MakeSound,该方法输出Sound的值。在Main方法中,创建一个Animal对象,并设置其属性值,然后调用MakeSound方法。

答案:

using System;

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Animal myAnimal = new Animal();
            myAnimal.Name = "Dog";
            myAnimal.Sound = "Bark";

            Console.WriteLine($"The {myAnimal.Name} goes:");
            myAnimal.MakeSound();
        }
    }

    class Animal
    {
        public string Name { get; set; }
        public string Sound { get; set; }

        public void MakeSound()
        {
            Console.WriteLine(Sound);
        }
    }
}

通过这个综合练习,巩固了对类、属性和方法的理解,并将这些概念结合起来创建了一个完整的程序。

For 循环和 While 循环的差别

for 循环

for循环通常用于当你知道循环的次数时。它由三个部分组成:初始化、条件和迭代。在for循环中,所有这些部分都在一行中定义,使得代码更加紧凑和清晰。

示例:

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

在这个示例中,i被初始化为0,循环继续执行直到i小于5,每次迭代后,i增加1。这个结构使得for循环非常适合用于需要明确的迭代次数的情况。

while 循环

while循环用于当循环的次数未知时,它会一直执行直到条件不再满足。while循环的条件在循环开始之前检查,如果条件为假,则循环体不会执行。

示例:

int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

在这个示例中,count从0开始,每次迭代后增加1,直到count不再小于5。while循环在循环开始之前检查条件,因此在条件首次为假时,循环体不会执行。

选择哪种循环?

选择for循环还是while循环通常取决于具体情况和个人偏好:

  • 使用for循环当你知道循环的次数,或者当你希望所有循环相关的代码(初始化、条件、迭代)都在一行中。
  • 使用while循环当你不知道循环的次数,或者当条件不满足时你希望循环立即停止。

这两种循环可以互换使用,但选择适合的循环可以使代码更加清晰和易于理解。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值