简体   繁体   English

C#不要覆盖重写的方法

[英]C# don't override overridden method

is there an attribute or pattern to tell the compiler don't allow override overridable method? 是否有一个attributepattern来告诉编译器不允许覆盖可重写方法?

For example: 例如:

Vehicle

public class Vehicle
{
    public virtual void Start() { }
}

Car

public class Car : Vehicle
{
    // ################
    [DontAllowOverrideAgain] //I need something like this attribute
    // ################
    public override void Start()
    {
        // Todo => codes that every car must invoke before start ...
        CarStart();
        // Todo => codes that every car must invoke after start ...
    }

    public virtual void CarStart() { }
}

CoupeCar

public class CoupeCar : Car
{
    // throw and error or show a message to developer
    public override void Start() { }

    public override void CarStart() { }
}

Sure, just create the first override as sealed , which would lead to a compile time failure that the developer can see 当然,只需将第一个替代创建为sealed ,这将导致开发人员可以看到的编译时失败

public class Car : Vehicle
{
    public sealed override void Start()
    {
        // Todo => codes that every car must invoke before start ...
        CarStart();
        // Todo => codes that every car must invoke after start ...
    }

    public virtual void CarStart() { }
}

Here you have it, use sealed 在这里,使用密封

Ref. 参考。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed

public class Car : Vehicle
{
     sealed protected override void Start()
    {
        // Todo => codes that every car must invoke before start ...
        CarStart();
        // Todo => codes that every car must invoke after start ...
    }

    public virtual void CarStart() { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM