C#中new, override, virtual的具体用法

本文详细解析C#中的new, override与virtual方法的作用与区别,通过实例代码展示它们如何影响方法调用和输出结果,提供深入理解C#面向对象编程的关键概念。

一句话:你是否真的了解new, override, virtual

下面代码的结果,如果基类使用接口代替,也是一样的效果。

主要注意看override或new了基类的方法后,调用方将子类对象转型为父类后的输出会有什么不同;

代码
class Program
{
static void Main(string[] args)
{
TestShape();
Console.WriteLine(
"TestShape end =============" + Environment.NewLine);
TestDerive();
Console.WriteLine(
"TestDerive end =============" + Environment.NewLine);
TestDerive2();
Console.WriteLine(
"TestDerive2 end =============" + Environment.NewLine);
Console.ReadKey();
}

private static void TestShape()
{
System.Collections.Generic.List
<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(
new Circle());
shapes.Add(
new Rectangle());
shapes.Add(
new Triangle());
shapes.Add(
new Diamond());
foreach (Shape s in shapes)
{
s.MethodVirtual();
s.Method();
Console.WriteLine();
}

}

private static void TestDerive()
{
Circle circle
= new Circle();
Rectangle rectangle
= new Rectangle();
Triangle triangel
= new Triangle();
Diamond diamond
= new Diamond();
circle.MethodVirtual();
circle.Method();
Console.WriteLine();
rectangle.MethodVirtual();
rectangle.Method();
Console.WriteLine();
triangel.MethodVirtual();
triangel.Method();
Console.WriteLine();
diamond.MethodVirtual();
diamond.Method();
Console.WriteLine();
}

private static void TestDerive2()
{
Circle circle
= new Circle();
PrintShape(circle);
Rectangle rectangle
= new Rectangle();
PrintShape(rectangle);
Triangle triangel
= new Triangle();
PrintShape(triangel);
Diamond diamond
= new Diamond();
PrintShape(diamond);
///out put:
//circle override MethodVirtual
//base Method call

//base MethodVirtual call
//base Method call

//base MethodVirtual call
//base Method call

//base MethodVirtual call
//base Method call
}

static void PrintShape(Shape sharpe)
{
sharpe.MethodVirtual();
sharpe.Method();
Console.WriteLine();
}
}

public class Shape
{
public virtual void MethodVirtual()
{
Console.WriteLine(
"base MethodVirtual call");
}

public void Method()
{
Console.WriteLine(
"base Method call");
}
}

///类描述:override了基类的virtual方法
///
///第一种使用方法:转型为父类
///sharp s = new Circle()
///s.MethodVirtual();
///s.Method();
///因为子类已经override了父类的MethodVirtual,所以即使子类转型为了sharp,调用的还是子类的方法
///out put:
///circle override MethodVirtual
///base Method call
///
///第二类使用方法:使用子类本身
///这很好理解,全部输出的是子类的方法
///Circle circle = new Circle();
///circle.MethodVirtual();
///circle.Method();
///out put:
///circle override MethodVirtual
///base Method call
class Circle : Shape
{
public override void MethodVirtual()
{
Console.WriteLine(
"circle override MethodVirtual");
}
}

///类描述:未做任何处理
///
///第一种使用方法
///sharp s = new Rectangle()
///s.MethodVirtual();
///s.Method();
///out put:
///base MethodVirtual call
///base Method call
///
///第二类使用方法:使用子类本身
///这很好理解,全部输出的是子类的方法
///Rectangle rectangle = new Rectangle();
///rectangle.MethodVirtual();
///rectangle.Method();
///out put:
///base MethodVirtual call
///base Method call
class Rectangle : Shape
{

}

///类描述:new了基类的虚方法即非虚方法
///
///第一种使用方法
///sharp s = new Triangle()
///s.MethodVirtual();
///s.Method();
///因为子类已经new了父类的方法,所以s输出的是父类的方法
///out put:
///base MethodVirtual call
///base Method call
///
///第二类使用方法:使用子类本身
///这很好理解,全部输出的是子类的方法
///Triangle triangel = new Triangle();
///triangel.MethodVirtual();
///triangel.Method();
///out put:
///triangle new MethodVirtual
///triangle new Method
class Triangle : Shape
{
public new void MethodVirtual()
{
Console.WriteLine(
"triangle new MethodVirtual");
}

public new void Method()
{
Console.WriteLine(
"triangle new Method");
}
}

///类描述:创建了基类方法相同的方法,未new及override
///编译器会做提示“隐藏继承”,并有如存在 new 关键字一样执行操作
///
///第一种使用方法
///sharp s = new Diamond()
///s.MethodVirtual();
///s.Method();
///因为默认new的效果,所以输出和显式new修饰的一样
///out put:
///base MethodVirtual call
///base Method call
///
///第二类使用方法:使用子类本身
///这很好理解,全部输出的是子类的方法
///Diamond diamond = new Diamond();
///diamond.MethodVirtual();
///diamond.Method();
///out put:
///Diamond default MethodVirtual
///Diamond default Method
class Diamond : Shape
{
public void MethodVirtual()
{
Console.WriteLine(
"Diamond default MethodVirtual");
}

public void Method()
{
Console.WriteLine(
"Diamond default Method");
}
}

 

<think>首先,用户的问题是:“我想理解C#virtualoverride关键字的用法和区别 请问C#virtualoverride关键字的作用及使用方法”。我需要基于提供的系统级指令和用户可见层的要求来回答。 系统级指令: - 所有行内数学表达式必须用$...$格式,但这里的问题是关于编程的C#关键字,可能不涉及数学表达式。所以,我应该避免不必要的数学表达式,除非有相关计算。 - 独立公式必须用$$...$$格式并单独成段,同样,可能不适用。 - LaTeX语法正确:确保任何LaTeX正确。 - 使用中文回答。 - 生成相关问题:在回答结束时生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。引用是基于提供的引用内容:[^1], [^2], [^3]。这些是关于C# virtual, abstract, override等的讨论。 用户可见层: - 回答结构清晰,帮助用户逐步解决问题。 - 尽量保证回答真实可靠。 - 参考站内引用:提供了[^1], [^2], [^3]的内容。 提供的引用: - [^1]: 讨论virtual关键字,虚函数与一般函数的区别。 - [^2]: 解释virtual, override, base关键字,抽象类和方法。 - [^3]: 给出代码示例使用virtualoverride。 我的回答需要结构化: 1. 解释virtual关键字的作用和用法。 2. 解释override关键字的作用和用法。 3. 讨论两者的区别。 4. 提供代码示例(基于引用[^3])。 5. 结束时生成相关问题。 使用中文回答。 步骤: 1. **介绍virtual关键字**: - virtual允许在基类中声明方法,以便派生类可以重写它。 - 它支持多态性。 - 引用[^1]:虚函数与一般函数的区别;成员字段和静态函数不能是virtual。 - 引用[^2]:virtual用于声明虚方法,允许子类重写。 2. **介绍override关键字**: - override用于派生类中重写基类的virtual方法。 - 它必须匹配基类方法的签名。 - 引用[^2]:override用于重写虚方法。 - 引用[^3]:代码示例。 3. **区别**: - virtual在基类中使用,表示方法可被重写。 - override在派生类中使用,表示重写基类的方法。 - 没有virtual的方法不能被override。 - 抽象方法必须被override。 4. **代码示例**: - 使用引用[^3]的代码,但简化并解释。 - 确保代码格式正确(如示例中所示)。 5. **添加引用标识**: - 在相关段落末尾添加[^1], [^2], [^3]自然地。 6. **生成相关问题**: - 在结束时,添加“§§相关问题§§”部分,列出2-3个相关问题。 结构回答: - 开头:简要介绍主题。 - 部分1:virtual关键字的作用和用法。 - 部分2:override关键字的作用和用法。 - 部分3:区别和关键点。 - 部分4:代码示例。 - 结尾:总结和生成相关问题。 确保回答真实可靠:基于提供的引用和标准C#知识。 最终输出格式: - 使用Markdown。 - 代码块用```python或```csharp(如示例)。 - 相关问题部分用“§§相关问题§§”。</think>### C#virtualoverride关键字的用法与区别 在C#面向对象编程中,`virtual`和`override`关键字是实现多态性的核心机制,允许派生类自定义基类行为。下面我将逐步解释它们的作用、使用方法和区别,确保回答基于可靠参考,并附上代码示例。所有解释均参考提供的站内引用内容[^1][^2][^3]。 #### 1. **virtual关键字的作用和用法** - **作用**:`virtual`用于在基类中声明一个方法为虚方法(virtual method),表示该方法可以被派生类重写。这支持运行时多态性:当调用方法时,实际执行的是对象实际类型(而非引用类型)的版本[^1][^2]。 - 虚函数与一般函数的区别在于:一般函数在编译时绑定(静态绑定),而虚函数在运行时动态绑定,允许更灵活的继承[^1]。 - 注意:`virtual`只适用于实例方法(非静态方法),成员字段、静态方法或构造函数不能声明为`virtual`[^1]。 - **使用方法**: - 在基类方法前添加`virtual`关键字。 - 语法示例:`public virtual void MethodName() { ... }`。 - 派生类可以选择是否重写该方法;如果不重写,则调用基类实现。 #### 2. **override关键字的作用和用法** - **作用**:`override`用于在派生类中重写基类的`virtual`方法,提供新的实现。这确保了当通过基类引用调用方法时,实际执行派生类的版本,实现多态行为[^2][^3]。 - 重写必须完全匹配基类方法的签名(名称、参数和返回类型)。 - 重写后的方法自动成为虚方法,可以被进一步重写(如多层继承)[^3]。 - **使用方法**: - 在派生类方法前添加`override`关键字。 - 语法示例:`public override void MethodName() { ... }`。 - 可以使用`base`关键字在派生类中调用基类版本(例如`base.MethodName()`),用于部分重用逻辑[^2]。 #### 3. **virtualoverride的区别** - **关键区别**: - `virtual`在基类中使用,表示“此方法可被重写”;`override`在派生类中使用,表示“此方法重写了基类方法”。 - 没有`virtual`的方法不能被`override`;如果基类方法非`virtual`,派生类定义同名方法会隐藏它(使用`new`关键字),而非重写[^1][^2]。 - 抽象方法(`abstract`)必须被`override`,但`virtual`方法是可选的;`virtual`提供默认实现,而`abstract`强制派生类提供实现[^2]。 - **多态性体现**:通过`virtual`和`override`组合,C#实现动态绑定。例如,当基类引用指向派生类对象时,调用`override`方法会执行派生类版本,而非基类版本[^3]。 #### 4. **代码示例** 基于引用[^3]的示例,我简化并解释一个典型场景:多层继承中`virtual`和`override`的行为。 ```csharp using System; // 基类,声明虚方法 class MyBaseClass { public virtual void Print() // virtual关键字声明可重写方法 { Console.WriteLine("This is the base class"); } } // 派生类,重写基类方法 class MyDerivedClass : MyBaseClass { public override void Print() // override关键字重写 { Console.WriteLine("This is the derived class"); } } // 进一步派生类,重写上一层方法 class SecondDerivedClass : MyDerivedClass { public override void Print() // 再次override,依旧是虚方法 { Console.WriteLine("This is the second derived class"); } } internal class Program { static void Main(string[] args) { SecondDerivedClass myDerived = new SecondDerivedClass(); MyBaseClass myBaseClass = (MyBaseClass)myDerived; // 转换为基类引用 myDerived.Print(); // 输出: This is the second derived class (直接调用派生类对象) myBaseClass.Print(); // 输出: This is the second derived class (通过基类引用调用,动态绑定到实际类型) } } ``` **解释**: - 当`myBaseClass.Print()`被调用时,尽管引用类型是`MyBaseClass`,但对象实际类型是`SecondDerivedClass`,因此执行重写后的版本。这演示了运行时多态性[^3]。 - 如果移除`override`,编译器会报错或行为改变(如使用`new`关键字隐藏方法)。 #### 总结 `virtual`和`override`关键字共同实现C#的多态继承:`virtual`在基类中标记可扩展点,`override`在派生类中提供定制实现。区别在于`virtual`是“可重写”的声明,而`override`是“重写”的执行。正确使用它们能提升代码的灵活性和可维护性[^1][^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值