C# 入门教程笔记

C# 入门教程笔记

下面是一个全面的 C# 教程,适合初学者和有一定编程经验的人士。C# 是一种由微软开发的面向对象的编程语言,广泛用于 Windows 应用程序开发、游戏开发(特别是 Unity 引擎)、Web 应用程序开发等。要想深入了解和学习请参考C#电子教程-语法api调用手册C#经典项目实例汇总源代码C#编程从入门到精通

1. 简介
  • 定义:C# 是一种现代的、通用的、面向对象的编程语言。
  • 用途
    • Windows 桌面应用程序开发。
    • Web 应用程序开发(如 ASP.NET)。
    • 游戏开发(如 Unity 引擎)。
    • 移动应用开发(如 Xamarin)。
    • 企业级应用开发。
  • 特点
    • 语法简洁清晰。
    • 支持面向对象编程。
    • 自动垃圾回收。
    • 丰富的标准库。
    • 跨平台支持(通过 .NET Core 和 .NET 5+)。
2. 安装 Visual Studio
在 Windows 上安装
  • 访问 Visual Studio 官方网站 下载并安装最新版本的 Visual Studio。
  • 在安装过程中,选择“ASP.NET 和 Web 开发”或“.NET 桌面开发”工作负载。
在 macOS 上安装
在 Linux 上安装
  • 使用包管理器安装 .NET SDK:
    sudo apt-get update
    sudo apt-get install dotnet-sdk-5.0
    
3. 第一个 C# 程序
创建项目目录
  • 打开 Visual Studio 并创建一个新的控制台应用程序项目。
  • 选择 “File” -> “New” -> “Project”。
  • 选择 “Console App (.NET Core)” 或 “Console App (.NET Framework)”,然后点击 “Next”。
  • 输入项目名称(例如 HelloWorld),选择项目位置,然后点击 “Create”。
编写第一个程序
  • Program.cs 文件中,你会看到以下代码:
    using System;
    
    namespace HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello, World!");
            }
        }
    }
    
运行程序
  • 点击工具栏上的“Start”按钮(绿色三角形)或按 F5 键来运行程序。
  • 你应该会看到输出 Hello, World!
4. C# 基础语法
注释
  • 单行注释使用 //
  • 多行注释使用 /* ... */
// 这是单行注释
/*
这是多行注释
可以跨越多行
*/
变量
  • 变量需要显式声明类型。
  • 支持动态类型(使用 var 关键字)。
int a = 42;
double b = 3.14;
bool c = true;
string d = "Hello, World!";

var e = 10; // e 的类型为 int
var f = "Hello"; // f 的类型为 string
数据类型
  • 基本类型int, float, double, bool, char, string
  • 复合类型array, list, dictionary
int myInt = 42;
double myDouble = 3.14;
bool myBool = true;
string myString = "Hello, World!";

int[] myArray = { 1, 2, 3 };
List<int> myList = new List<int> { 1, 2, 3 };
Dictionary<string, int> myDict = new Dictionary<string, int> { { "one", 1 }, { "two", 2 } };
字符串
  • 使用双引号 " 定义字符串。
  • 字符串插值使用 $ 符号。
string s1 = "Hello, World!";
string name = "Alice";
string s2 = $"Hello, {name}!";
控制结构
条件语句
  • if...else 语句
int age = 18;

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a minor.");
}
循环
  • for 循环
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i); // 输出: 0 1 2 3 4
}
  • while 循环
int i = 0;
while (i < 5)
{
    Console.WriteLine(i); // 输出: 0 1 2 3 4
    i++;
}
  • foreach 循环
int[] numbers = { 1, 2, 3 };

foreach (int number in numbers)
{
    Console.WriteLine(number); // 输出: 1 2 3
}
5. 函数
定义函数
  • 使用 void 关键字定义无返回值的函数。
  • 使用其他类型定义有返回值的函数。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string result = Greet("Alice");
            Console.WriteLine(result); // 输出: Hello, Alice!
        }

        static string Greet(string name)
        {
            return $"Hello, {name}!";
        }
    }
}
默认参数
  • 函数可以有默认参数值。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string result1 = Greet("Alice"); // 使用默认问候语
            string result2 = Greet("Bob", "Hi there"); // 使用自定义问候语
            Console.WriteLine(result1); // 输出: Hello, Alice!
            Console.WriteLine(result2); // 输出: Hi there, Bob!
        }

        static string Greet(string name, string greeting = "Hello")
        {
            return $"{greeting}, {name}!";
        }
    }
}
可变参数
  • 使用 params 关键字定义可变参数。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = Sum(1, 2, 3, 4);
            Console.WriteLine(sum); // 输出: 10
        }

        static int Sum(params int[] numbers)
        {
            int total = 0;
            foreach (int number in numbers)
            {
                total += number;
            }
            return total;
        }
    }
}
6. 类和对象
定义类
  • 使用 class 关键字定义类。
using System;

namespace HelloWorld
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void SayHello()
        {
            Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("Alice", 30);
            p.SayHello(); // 输出: Hello, my name is Alice and I am 30 years old.
        }
    }
}
继承
  • 使用 : 符号定义子类,并使用 base 关键字调用父类的方法。
using System;

namespace HelloWorld
{
    class Student : Person
    {
        public string Grade { get; set; }

        public Student(string name, int age, string grade) : base(name, age)
        {
            Grade = grade;
        }

        public new void SayHello()
        {
            Console.WriteLine($"Hello, I'm a student named {Name} and I am {Age} years old, in grade {Grade}.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student("Bob", 20, "A");
            s.SayHello(); // 输出: Hello, I'm a student named Bob and I am 20 years old, in grade A.
        }
    }
}
7. 文件操作
读取文件
  • 使用 System.IO 命名空间中的 StreamReader 读取文件。
using System;
using System.IO;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string content = reader.ReadToEnd();
                    Console.WriteLine(content);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}
写入文件
  • 使用 System.IO 命名空间中的 StreamWriter 写入文件。
using System;
using System.IO;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    writer.WriteLine("This is some text.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}
追加内容
  • 使用 System.IO 命名空间中的 StreamWriter 以追加模式写入文件。
using System;
using System.IO;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                using (StreamWriter writer = new StreamWriter(filePath, append: true))
                {
                    writer.WriteLine("\nThis is additional text.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}
8. 异常处理
捕获异常
  • 使用 try...catch 语句捕获和处理异常。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int result = Divide(10, 0);
                Console.WriteLine(result);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An unexpected error occurred: {ex.Message}");
            }
        }

        static int Divide(int a, int b)
        {
            if (b == 0)
            {
                throw new DivideByZeroException("Cannot divide by zero.");
            }
            return a / b;
        }
    }
}
抛出异常
  • 使用 throw 关键字抛出异常。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int result = Divide(10, 0);
                Console.WriteLine(result);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }

        static int Divide(int a, int b)
        {
            if (b == 0)
            {
                throw new DivideByZeroException("Cannot divide by zero.");
            }
            return a / b;
        }
    }
}
9. 标准库
数学运算
  • 使用 System 命名空间中的 Math 类进行数学运算。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            double squareRoot = Math.Sqrt(16);
            double pi = Math.PI;

            Console.WriteLine($"Square root of 16: {squareRoot}"); // 输出: 4.0
            Console.WriteLine($"Pi: {pi}"); // 输出: 3.141592653589793
        }
    }
}
时间和日期
  • 使用 System 命名空间中的 DateTime 类处理时间和日期。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            Console.WriteLine(now); // 输出当前时间
        }
    }
}
随机数
  • 使用 System 命名空间中的 Random 类生成随机数。
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int randomNumber = random.Next(1, 11); // 生成 1 到 10 之间的随机整数
            Console.WriteLine(randomNumber);
        }
    }
}
10. LINQ (Language Integrated Query)
查询集合
  • 使用 LINQ 查询集合数据。
using System;
using System.Linq;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var evenNumbers = from num in numbers
                              where num % 2 == 0
                              select num;

            Console.WriteLine("Even numbers:");
            foreach (var num in evenNumbers)
            {
                Console.WriteLine(num);
            }
        }
    }
}
查询数据库
  • 使用 LINQ to SQL 或 Entity Framework 查询数据库。
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new MyDbContext())
            {
                var customers = from c in context.Customers
                               where c.Age > 30
                               select c;

                Console.WriteLine("Customers over 30 years old:");
                foreach (var customer in customers)
                {
                    Console.WriteLine($"{customer.Name} ({customer.Age})");
                }
            }
        }
    }

    public class MyDbContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

总结

以上是一个全面的 C# 入门教程,涵盖了从基础语法到类和对象、文件操作、异常处理、标准库和 LINQ 的基本步骤。通过这些基础知识,你可以开始编写简单的 C# 程序,并进一步探索更复杂的功能和创意。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanxbl957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值