C#中override

override(C# 参考)

要扩展或修改继承的方法、属性、索引器或事件的抽象实现或虚实现,必须使用override 修饰符。


abstract class ShapesClass
{
    abstract public int Area();
}
class Square : ShapesClass
{
    int side = 0;

    public Square(int n)
    {
        side = n;
    }
    // Area method is required to avoid
    // a compile-time error.
    public override int Area()
    {
        return side * side;
    }

    static void Main() 
    {
        Square sq = new Square(12);
        Console.WriteLine("Area of the square = {0}", sq.Area());
    }

    interface I
    {
        void M();
    }
    abstract class C : I
    {
        public abstract void M();
    }

}
// Output: Area of the square = 144





对日期的操作格式

string dtCheckNow = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), dtToday = System.DateTime.Now.ToString("yyyy-MM-dd"), dtTemorrow = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");




C#,`override`关键字用于在派生类重写基类的虚方法、属性或索引器。通过使用`override`关键字,我们可以在派生类提供自己的实现,覆盖基类的默认实现。 要使用`override`关键字,需要满足以下条件: 1. 基类的方法、属性或索引器必须被声明为`virtual`或`abstract`。 2. 派生类的方法、属性或索引器必须具有相同的名称、返回类型和参数列表。 下面是一个示例,演示了如何在派生类使用`override`关键字来重写基类的虚方法: ```csharp class Animal { public virtual void MakeSound() { Console.WriteLine("The animal makes a sound"); } } class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks"); } } class Program { static void Main(string[] args) { Animal animal = new Animal(); animal.MakeSound(); // 输出: The animal makes a sound Dog dog = new Dog(); dog.MakeSound(); // 输出: The dog barks Animal animalDog = new Dog(); animalDog.MakeSound(); // 输出: The dog barks } } ``` 在上面的示例,`Animal`类的`MakeSound`方法被声明为`virtual`,表示它可以被派生类重写。`Dog`类继承自`Animal`类,并使用`override`关键字重写了`MakeSound`方法。在`Main`方法,我们创建了一个`Animal`对象和一个`Dog`对象,并分别调用它们的`MakeSound`方法。由于`Dog`类重写了`MakeSound`方法,所以在调用`dog.MakeSound()`时输出的是"The dog barks"。 此外,还可以使用`override`关键字重写基类的属性和索引器。重写属性和索引器的语法与重写方法类似。 希望这个例子能够帮助你理解`override`关键字在C#的用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值