田敏
返回博客列表
技术

普通方法和虚方法

田敏
2024-12-101 分钟阅读
.NETC#Backend

在 C# 中,抽象类中的普通方法和虚方法有以下主要区别:


1. 普通方法(非虚方法)

  • 普通方法是标准的类方法,具有具体的实现。
  • 子类可以直接使用父类中的普通方法而无需重写。
  • 如果子类希望更改普通方法的行为,必须通过**“隐藏”**来重新实现它(用 new 关键字),而不是重写。

示例:

public abstract class AbstractClass
{
    public void RegularMethod()
    {
        Console.WriteLine("This is a regular method in the abstract class.");
    }
}

public class DerivedClass : AbstractClass
{
    public new void RegularMethod()
    {
        Console.WriteLine("This is a new implementation in the derived class.");
    }
}

// 使用
AbstractClass obj = new DerivedClass();
obj.RegularMethod(); // 输出:This is a regular method in the abstract class.
  • **限制:**父类和子类的普通方法是两套逻辑,调用的是父类的实现,除非强制使用 new 关键字改变行为。

2. 虚方法

  • 虚方法是用 virtual 修饰的方法,定义在基类中,可以在子类中被重写
  • 虚方法的核心目的是允许子类通过 override 关键字重写基类的方法。
  • 如果没有在子类中重写虚方法,调用时使用基类的实现。

示例:

public abstract class AbstractClass
{
    public virtual void VirtualMethod()
    {
        Console.WriteLine("This is a virtual method in the abstract class.");
    }
}

public class DerivedClass : AbstractClass
{
    public override void VirtualMethod()
    {
        Console.WriteLine("This is the overridden method in the derived class.");
    }
}

// 使用
AbstractClass obj = new DerivedClass();
obj.VirtualMethod(); // 输出:This is the overridden method in the derived class.
  • **行为:**子类通过重写,修改了基类虚方法的行为,实际调用的是子类实现。

3. 区别总结

| 特性 | 普通方法 | 虚方法 | | ------------------ | ----------------------------------------------------- | -------------------------------------- | | 修饰符 | 默认无修饰符 | 使用 virtual 修饰 | | 是否可被重写 | 不能直接被重写,必须使用 new 关键字隐藏行为 | 可在子类中用 override 关键字重写行为 | | 调用行为 | 调用具体对象类型的方法,如果有 new 隐藏则调用新实现 | 调用重写后的方法,遵循运行时多态性 | | 意图 | 提供固定行为,无需在子类中修改 | 提供默认行为,允许子类灵活更改 | | 运行时多态支持 | 不支持 | 支持 |


4. 何时使用普通方法和虚方法?

使用普通方法的场景:

  • 方法的行为是固定的,不需要子类改变。
  • 希望子类能够调用基类的实现,但不能改变它的逻辑。

使用虚方法的场景:

  • 提供一个默认实现,但允许子类根据需要修改实现。
  • 实现运行时的多态,子类可以根据具体类型改变方法的行为。

5. 扩展:抽象方法 vs 虚方法

  • 抽象方法是未实现的方法,必须在子类中重写。
  • 虚方法是已实现的方法,子类可以选择性地重写。

示例:

public abstract class AbstractClass
{
    public abstract void AbstractMethod(); // 必须重写

    public virtual void VirtualMethod()
    {
        Console.WriteLine("Virtual method in abstract class.");
    }
}
版权协议:MIT返回列表