欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > C# 【OOP(面向对象编程)教程】:第四章:类与对象

C# 【OOP(面向对象编程)教程】:第四章:类与对象

2025/9/16 23:13:57 来源:https://blog.csdn.net/weixin_49015143/article/details/139997131  浏览:    关键词:C# 【OOP(面向对象编程)教程】:第四章:类与对象
1. 类的定义

类是面向对象编程的基本单位,描述对象的属性和行为。一个类定义了对象的结构和方法。

  • 定义类
    public class Person {// 属性public string Name { get; set; }public int Age { get; set; }// 方法public void Greet() {Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");}
    }
    

在这个例子中,Person 类有两个属性 NameAge,以及一个方法 Greet

2. 对象的创建与使用

对象是类的实例,通过类创建对象,并使用对象访问类的属性和方法。

  • 创建对象

    Person person = new Person();
    person.Name = "Alice";
    person.Age = 30;// 使用对象
    person.Greet(); // 输出:Hello, my name is Alice and I am 30 years old.
    
  • 使用对象初始化器

    Person person = new Person {Name = "Bob",Age = 25
    };
    person.Greet(); // 输出:Hello, my name is Bob and I am 25 years old.
    
3. 构造函数

构造函数是类的一种特殊方法,在创建对象时自动调用,用于初始化对象。

  • 定义构造函数

    public class Person {// 属性public string Name { get; set; }public int Age { get; set; }// 构造函数public Person(string name, int age) {Name = name;Age = age;}// 方法public void Greet() {Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");}
    }
    
  • 使用构造函数创建对象

    Person person = new Person("Charlie", 35);
    person.Greet(); // 输出:Hello, my name is Charlie and I am 35 years old.
    
4. 方法与属性

方法和属性是类的重要组成部分,用于定义类的行为和状态。

  • 属性的定义和使用

    public class Person {// 自动实现的属性public string Name { get; set; }public int Age { get; set; }
    }Person person = new Person();
    person.Name = "David";
    person.Age = 40;
    Console.WriteLine(person.Name); // 输出:David
    Console.WriteLine(person.Age); // 输出:40
    
  • 方法的定义和使用

    public class Person {// 属性public string Name { get; set; }public int Age { get; set; }// 方法public void Greet() {Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");}
    }Person person = new Person {Name = "Eve",Age = 22
    };
    person.Greet(); // 输出:Hello, my name is Eve and I am 22 years old.
    
  • 带参数的方法

    public class Person {// 属性public string Name { get; set; }public int Age { get; set; }// 带参数的方法public void UpdateAge(int newAge) {Age = newAge;}
    }Person person = new Person {Name = "Frank",Age = 28
    };
    person.UpdateAge(29);
    Console.WriteLine(person.Age); // 输出:29
    

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词