首页 > 编程语言 >C#-sealed 封装类的使用

C#-sealed 封装类的使用

时间:2022-12-19 17:36:37浏览次数:37  
标签:封装 WriteLine C# void System M1 sealed Console public

示例1 :

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

namespace singleton
{
public class myClass1
{
    /// <summary>/// 虚方法,用来显示信息/// </summary>
    public virtual void ShowInfo()
    {
    }
}
public sealed class myClass2 : myClass1       //密封类,继承自myClass1
{
    private string id = "";
    //string类型变量,用来记录编号
    private string name = "";
    //string类型变量,用来记录名称
    /// <summary>/// 编号属性/// 
    ///</summary>
    public string ID
    {
        get { return id; }
        set { id = value; }
    }
    /// <summary>/// 名称属性/// </summary>
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    /// <summary>/// 密封并重写基类中的ShowInfo方法/// 
    /// </summary>
    public sealed override void ShowInfo()
    {
        Console.WriteLine(ID + " " + Name);
    }
}
class Program
{
    static void Main(string[] args)
    {
        myClass2 myclass2 = new myClass2();
        //实例化密封类对象
        myclass2.ID = "BH0001";  
        //为密封类中的编号属性赋值
        myclass2.Name = "TM";              //为密封类中的名称属性赋值
        myclass2.ShowInfo();               //调用密封类中的密封方法} 
    }
}
}

 

示例2:

 

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

namespace singleton
{
    class Program
    {
        public class A
        {
            protected virtual void M() { Console.WriteLine("A.M()"); }
            protected virtual void M1() { Console.WriteLine("A.M1()"); }
        }

        public class B : A
        {
            protected sealed override void M() { Console.WriteLine("B.M()"); }
            protected override void M1() { Console.WriteLine("B.M1()"); }
        }

        public sealed class C : B
        {
            /* ConsoleApplication1.MSFun.Sealed.C.M()':
            * cannot override inherited member 'ConsoleApplication1.MSFun.Sealed.B.M()'
            * because it is sealed */
            //protected override void M() { Console.WriteLine("C.M()"); }

            public int gl;
            public void methodC()
            {
                M1();
                Console.WriteLine("ok it's C method" + gl);
            }
            protected override void M1() { Console.WriteLine("C.M1()"); }
        }        static void Main(string[] args)
        {

            C ci = new C();
            ci.gl = 5;
            ci.methodC();



        }
    }
}


 

解释:类A中有虚方法 M 和 M1 , B 继承A类,将其中M方法声明为 sealed ,M1方法不变。C继承B,因为M使用了sealed 关键字,所以在C中无法重写M方法。但是可以重写M1方法。

标签:封装,WriteLine,C#,void,System,M1,sealed,Console,public
From: https://blog.51cto.com/u_15917617/5953249

相关文章