C#在方法或属性中使用sealed时的操作与原理

C#在方法或属性中使用sealed时的操作与原理

2014年12月03日 19:26:56 成成_Baby 阅读数 2126

在《C#高级编程》第100页中间部分提到”要在方法或属性上使用sealed关键字,必需先从基类上把它声明为要重写的方法或属性。如果基类上不希望有重写的方法或属性,就不要把它声明为virtual。“

这一句话有点绕口,研究了很长时间才搞懂,假设一个类MyClass中存在sealed方法MyMethod或sealed属性MyProperty,那么,存在两种可能:

(1)MyClass未显式定义基类,那么.NET默认System.Object类为MyClass类的基类,且在Object类中存在MyMethod或MyProperty,并且它们被声明为virtual,在MyClass类中,MyMethod或MyProperty声明且定义为override。若Object类中不存在MyMethod或MyProperty就会产生编译错误。


 
  1. namespace test

  2. {

  3. class MyClass

  4. {

  5. public sealed override void MyMethod()

  6. {

  7. }

  8. }

  9. class Program

  10. {

  11. public static int Main()

  12. {

  13. return 0;

  14. }

  15. }

  16. }

编译信息如下: test.cs(5,31): error CS0115: “test.MyClass.MyMethod()”:
        没有找到适合的方法来重写

(2)MyClass定义基类BaseClass,则在BaseClass类中存在MyMethod或MyProperty,并且它们被声明为virtual,在MyClass类中,MyMethod或MyProperty声明且定义为override。若BaseClass类中不存在MyMethod或MyProperty就会产生编译错误。

 


 
  1. using System;

  2. namespace Test

  3. {

  4. class Father

  5. {

  6. }

  7. class Base : Father

  8. {

  9. public sealed override void MyProperty() { get; set; }

  10. }

  11. public class Program

  12. {

  13. static int Main()

  14. {

  15. return 0;

  16. }

  17. }

  18. }

编译信息如下: test.cs(9,31): error CS0115: “Test.MyClass.MyProperty()”:
        没有找到适合的方法来重写

posted @ 2019-07-14 10:31  grj001  阅读(91)  评论(0编辑  收藏  举报