C# 中的密封方法

发布于 2024-10-01 12:48:44 字数 737 浏览 0 评论 0原文

我是 C# 的新手。我正在阅读有关 Sealed 关键字的内容。我已经了解了密封类。我读过一行关于 Sealed 方法的内容,我们也可以在其中创建 Sealed 方法。该行是 (通过将方法声明为密封的,我们可以避免进一步重写此方法。) 我创建了一个演示,但不明白上面一行和密封方法使用的含义。下面是我的代码:-

using System;

namespace ConsoleApplication2
{
    class Program:MyClass
    {
        public override sealed void Test()
        {
            Console.WriteLine("My class Program");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Test();
            Console.ReadLine();
        }
    }

    class MyClass
    {
        public virtual void Test()
        {
            Console.WriteLine("My class Test");
        }
    }


}

请告诉我为什么我们使用密封方法以及密封方法的优点是什么。

I am a newbie in C#.I am reading about Sealed keyword.I have got about sealed class.I have read a line about Sealed method where we can make Sealed method also.The line was (By declaring method as sealed, we can avoid further overriding of this method.)
I have created a demo but didn't understand that the meaning of above line and sealed method use. Below is my code:-

using System;

namespace ConsoleApplication2
{
    class Program:MyClass
    {
        public override sealed void Test()
        {
            Console.WriteLine("My class Program");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Test();
            Console.ReadLine();
        }
    }

    class MyClass
    {
        public virtual void Test()
        {
            Console.WriteLine("My class Test");
        }
    }


}

Please tell me why we use Sealed methods and what are the advantages of Sealed methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

输什么也不输骨气 2024-10-08 12:48:44

好吧,您仅使用两个继承级别进行测试,并且还没有达到“进一步重写”方法的程度。如果将其设置为三个,您可以看到 sealed 的作用:

class Base {
   public virtual void Test() { ... }
}
class Subclass1 : Base {
   public sealed override void Test() { ... }
}
class Subclass2 : Subclass1 {
   public override void Test() { ... } // Does not compile!
   // If `Subclass1.Test` was not sealed, it would've compiled correctly.
}

Well, you are testing with only two levels of inheritance, and you are not getting to the point that you're "further overriding" a method. If you make it three, you can see what sealed does:

class Base {
   public virtual void Test() { ... }
}
class Subclass1 : Base {
   public sealed override void Test() { ... }
}
class Subclass2 : Subclass1 {
   public override void Test() { ... } // Does not compile!
   // If `Subclass1.Test` was not sealed, it would've compiled correctly.
}
苏辞 2024-10-08 12:48:44

密封类是不能是另一个更派生类的基类的类。

未密封类中的密封方法是不能在此类的派生类中重写的方法。

为什么我们使用密封方法?密封法有什么优点?

那么,为什么要使用虚拟方法呢? 提供一个可以自定义类行为的点。那么为什么要使用密封方法呢? 提供一个保证点,保证任何派生类与此方法相关的行为不会发生进一步的更改

可以自定义类行为的点有用,但危险。它们很有用,因为它们使派生类能够更改基类的行为。它们很危险...等等...因为它们使派生类能够改变基类的行为。虚拟方法基本上允许第三方让您的类执行您从未预料到或测试过的疯狂事情。

我喜欢编写符合我预期和测试结果的代码。密封方法允许您继续允许类的某些部分被重写,同时使密封方法具有有保证的、可测试的、稳定的行为,无法进一步自定义。

A sealed class is a class which cannot be a base class of another more derived class.

A sealed method in an unsealed class is a method which cannot be overridden in a derived class of this class.

Why do we use sealed methods? What are the advantages of sealed methods?

Well, why do you use virtual methods? To provide a point at which behaviour of a class can be customized. So why do you use sealed methods? To provide a point at which you are guaranteed that no further changes will occur in the behaviour of any derived class with respect to this method.

Points where the behaviour of a class can be customized are useful but dangerous. They are useful because they enable derived classes to change behaviour of the base class. They are dangerous... wait for it... because they enable derived classes to change behaviour of the base class. Virtual methods basically allow third parties to make your classes do crazy things that you never anticipated or tested.

I like writing code that does what I anticipate and what I tested. Sealing a method allows you to continue to allow parts of the class to be overridden while making the sealed methods have guaranteed, testable, stable behaviour that cannot be further customized.

难以启齿的温柔 2024-10-08 12:48:44

那么,如果您不希望任何派生类进一步重写您的方法,您只需在方法上使用“sealed”。如果方法未声明为虚拟方法且未覆盖另一个虚拟方法,则默认情况下方法是密封的。 (在 Java 中,方法默认是虚拟的 - 要实现“默认”C# 行为,您必须将方法标记为 final。)

我个人喜欢仔细控制继承 - 我更喜欢将整个类密封在其中可能的。但是,在某些情况下,您仍然希望允许继承,但要确保某些方法不会被进一步重写。一种用途可能是有效模板化方法,例如用于诊断:

public sealed override void Foo(int x)
{
    Log("Foo called with argument: {0}", x);
    FooImpl(x);
    Log("Foo completed");
}

protected abstract void FooImpl(int x);

现在子类不能覆盖 < code>Foo 直接 - 他们必须重写 FooImpl,因此当其他代码调用 Foo 时,我们的行为将始终被执行。

当然,模板化可能是出于其他原因,例如强制执行参数验证的某些方面。

根据我的经验,密封方法并不经常使用,但我很高兴有这种能力。 (我只是希望默认情况下类是密封的,但那是另一回事了。)

Well, you'd only use "sealed" on a method if you didn't want any derived classes to further override your method. Methods are sealed by default, if they're not declared as virtual and not overriding another virtual method. (In Java, methods are virtual by default - to achieve "default" C# behaviour you have to mark a method as final.)

Personally I like to control inheritance carefully - I prefer whole classes to be sealed where possible. However, in some cases you still want to allow inheritance, but ensure that some methods aren't overridden further. One use might be to effectively template the method, e.g. for diagnostics:

public sealed override void Foo(int x)
{
    Log("Foo called with argument: {0}", x);
    FooImpl(x);
    Log("Foo completed");
}

protected abstract void FooImpl(int x);

Now subclasses can't override Foo directly - they'd have to override FooImpl, so our behaviour will always be executed when other code calls Foo.

The templating could be for other reasons of course - for example to enforce certain aspects of argument validation.

In my experience sealed methods aren't used terribly often, but I'm glad the ability is there. (I just wish classes were sealed by default, but that's another conversation.)

贪恋 2024-10-08 12:48:44

现在,如果您声明 Program 的子类,您将无法重写 Test 方法,这就是重点。

在大多数情况下,您不需要密封方法,但当您为第三方开发人员必须扩展以创建自己的插件的某些插件系统开发基类时,它们可以证明自己是有用的。您可以保留一些服务数据,例如插件名称以及是否启用,并使用密封的方法和属性来完成此操作,这样插件开发人员就不会弄乱它。这是密封成员派上用场的一种情况

Now if you declare a subclass of Program you won't be able to override the Test method, that's the point.

In most cases you won't need sealed methods but they can prove themselves useful when you're developing a base class for some plugin system that third-party developers have to extend in order to create their own plugin. You can keep some service data like plugin name and whether it is enabled and use sealed methods and properties to do it, so plugin developers won't mess with it. That's one case when sealed members come handy

感情废物 2024-10-08 12:48:44

密封方法

密封方法用于定义虚拟方法的重写级别。

Sealed 关键字始终与 override 关键字一起使用。

密封法实际演示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {

            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }

       public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        }

       //public class ThirdClass : DerivedClass
       //{

       //    public override void Display()
       //    {
       //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
       //    }
       //}

        static void Main(string[] args)
        {

            DerivedClass ob1 = new DerivedClass();
            ob1.Display();

            Console.ReadLine();
        }
    }
}

Sealed Methods

Sealed method is used to define the overriding level of a virtual method.

Sealed keyword is always used with override keyword.

Practical demonstration of sealed method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {

            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }

       public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        }

       //public class ThirdClass : DerivedClass
       //{

       //    public override void Display()
       //    {
       //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
       //    }
       //}

        static void Main(string[] args)
        {

            DerivedClass ob1 = new DerivedClass();
            ob1.Display();

            Console.ReadLine();
        }
    }
}
把时间冻结 2024-10-08 12:48:44

C# 拥有它是因为 Java 具有相同的功能(final 方法)。我从未见过合法用途。

如果您不想允许扩展,则应将整个类标记为sealed,而不仅仅是一个方法。

C# has it because Java has an identical feature (final methods). I've never seen a legitimate use.

If you don't want to permit extension, the whole class should be marked sealed and not just one method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文