新腾讯网友 发表于 前天 16:25

C# 面向对象编程的三大支柱:封装、继承与多态

面向对象编程(OOP)是一种广泛使用的编程范式,它通过封装、继承和多态这三大支柱来构建灵活且可维护的代码结构。本文将详细介绍这三大支柱在C#语言中的应用,并通过示例代码展示它们的具体实现。
一、封装(Encapsulation)

封装是指将对象的属性(字段)和行为(方法)结合在一起,并对外部隐藏对象的具体实现细节,仅暴露必要的接口供外部使用。封装提高了代码的安全性和可维护性。
示例代码

using System;

namespace EncapsulationExample
{
    class Person
    {
        // 私有字段
        private string name;
        private int age;

        // 公共属性,通过get和set访问器控制字段的访问
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Age
        {
            get { return age; }
            set
            {
                // 添加逻辑校验,例如年龄应为非负数
                if (value >= 0)
                    age = value;
                else
                    throw new ArgumentException("Age must be non-negative.");
            }
        }

        // 方法
        public void DisplayInfo()
        {
            Console.WriteLine($"Name: {name}, Age: {age}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Name = "Alice";
            person.Age = 30;
            person.DisplayInfo();

            // 尝试设置非法年龄会抛出异常
            try
            {
                person.Age = -5;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}二、继承(Inheritance)

继承允许一个类(子类)继承另一个类(父类)的属性和方法,从而实现代码的重用和扩展。子类可以新增或重写父类的方法,但必须遵守父类定义的接口契约。
示例代码

using System;

namespace InheritanceExample
{
    // 父类
    class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Eating...");
        }
    }

    // 子类
    class Dog : Animal
    {
        // 新增方法
        public void Bark()
        {
            Console.WriteLine("Barking...");
        }

        // 重写父类方法
        public new void Eat()
        {
            Console.WriteLine("Dog is eating specific food...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            dog.Eat();  // 调用子类的方法
            dog.Bark();
        }
    }
}三、多态(Polymorphism)

多态是指允许使用对象的某个基类引用来指向其任何派生类的对象,并通过这个基类引用调用派生类中重写的方法。多态性使得代码更加灵活和可扩展。
示例代码

using System;

namespace PolymorphismExample
{
    // 抽象父类
    abstract class Shape
    {
        // 抽象方法
        public abstract double GetArea();
    }

    // 子类:圆形
    class Circle : Shape
    {
        public double Radius { get; set; }

        public override double GetArea()
        {
            return Math.PI * Radius * Radius;
        }
    }

    // 子类:矩形
    class Rectangle : Shape
    {
        public double Width { get; set; }
        public double Height { get; set; }

        public override double GetArea()
        {
            return Width * Height;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 多态性:使用基类引用来指向派生类对象
            Shape circle = new Circle { Radius = 5 };
            Shape rectangle = new Rectangle { Width = 4, Height = 6 };

            Console.WriteLine($"Circle Area: {circle.GetArea()}");
            Console.WriteLine($"Rectangle Area: {rectangle.GetArea()}");
        }
    }
}总结

封装、继承和多态是面向对象编程的三大基本支柱,它们在C#中得到了充分的支持。通过封装,我们可以保护对象的内部状态;通过继承,我们可以重用和扩展现有的代码;通过多态,我们可以编写更加灵活和可扩展的代码。理解和掌握这三大支柱,对于编写高质量的C#程序至关重要。希望本文的示例代码能够帮助读者更好地理解和应用这些概念。

来源:https://www.cnblogs.com/lyl6796910/p/18418833
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: C# 面向对象编程的三大支柱:封装、继承与多态