C#调用父类的父类的方法,甚至祖父类的函数

C#怎么调用父类甚至祖父类的虚函数

在项目开发的时候,有类的继承关系,但是,有时候我们就是需要调用父类或祖父类的方法,怎么办呢?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication2
{
    class Program
    {
        class S1
        {
            public virtual void Method()
            {
                Console.WriteLine("这是S1实例方法");
            }
        }
 
        class S2:S1
        {
            public virtual void Method()
            {
                Console.WriteLine("这是S2实例方法");
            }
        }
 
        class S3 : S2
        {
            public  virtual void Method()
            {
                Console.WriteLine("这是S3实例方法");
            }
        }
 
        static void Main(string[] args)
        {
            S3 s = new S3();
            // 调用S3.Methoed
            s.Method();
 
            // 调用S2.Methoed
            ((S2)s).Method();
 
            // 调用S1.Methoed
            ((S1)s).Method();
        }
    }
}

运行结果

 

 

出处:https://zhidao.baidu.com/question/583835539787659325.html

=======================================================================================

C#调用父类的父类的方法

override一个C#函数时,如果想调用这个函数在父类的父类中相应的方法,可以将override关键字变成new,调用时将Object转义成父类的父类

class A
{
 public virtual void Func()
 {
  Console.WriteLine("A");
 }
}


class B:A
{
 public new void Func()
 {
  Console.WriteLine("B");
 }
}


class C:B
{
 public void Func()
 {
  A a = this as C;
  a.Func();   
 }
}

 

 

出处:https://www.cnblogs.com/mbskys/articles/643452.html

=======================================================================================

个人使用

 以上方法,都是使用的public修饰符的,如果是 protected 或 private 修饰符的怎么办呢?

我是在父类中使用了protected 的变量,使子类可以访问,如下:

 

    class A
    {
        protected virtual List<Class1> Func()
        {
            Console.WriteLine("A");
            return new List<Class1>();
        }
    }

    class B : A
    {
        protected List<Class1> BaseList = null;
        protected override List<Class1> Func()
        {
            BaseList = base.Func();
            // todo : 对BaseList数据加工处理,并返回新的List<Class1>
            return new List<Class1>();
        }
    }

    class C : B
    {
        protected override List<Class1> Func()
        {
            var aList = BaseList;
            var bList = base.Func();
            // todo : 再次对List<Class1>数据加工处理
            return new List<Class1>();
        }
    }

 

posted on 2022-12-02 09:15  jack_Meng  阅读(2096)  评论(0编辑  收藏  举报

导航