zoukankan      html  css  js  c++  java
  • 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()”:
            没有找到适合的方法来重写

  • 相关阅读:
    ffmpeg用法
    文本文件存储格式
    一个守护进程实例
    构造函数初始化列表问题
    Windows系统下远程Linux系统
    printStackTrace
    getParameter
    HTML5新增的属性和废除的属性
    oracle导出表结构及注释
    <input type="text" > size与width区别
  • 原文地址:https://www.cnblogs.com/grj001/p/12224762.html
Copyright © 2011-2022 走看看