• 隐藏基类的理解


    在派生类中继承基类的时候,也就继承基类的实现代码,所以在派生类中可以把有些方法隐藏掉(或者说可以直接使用)例如下面的隐藏,(为什么隐藏给的原因的是代码不像预期那样工作了)

    public class MyBaseClass
    {
    public void DoSomething()
    {
    // Base implementation.
    }
    }
    public class MyDerivedClass : MyBaseClass
    {
    public void DoSomething()
    {
    // Derived class implementation, hides base implementation.
    }
    }

    但是这样会出错的,如果我们无意间隐藏了一个需要使用的成员,这时候需要修正的。(如果系统提示隐藏了一个成员,而你又找不到问题所在,这就是你隐藏了基类的一个成员)但是如果你是故意想隐藏这个成员的话,那么需要在代码前加NEW的

    new public void DoSomething()
    {
    // Derived class implementation, hides base implementation.
    }

    当然也可以在派生类中重写基类的方法(前提基类的方法是抽象的虚拟的)见例子

    public class MyBaseClass
    {
    public virtual void DoSomething()
    {
    Console.WriteLine("Base imp");
    }
    }
    public class MyDerivedClass : MyBaseClass
    {
    public override void DoSomething()
    {
    Console.WriteLine("Derived imp");
    }
    }

    当然也可以用NEW,这时候基类方法就无所谓了见下例:

    public class MyBaseClass
    {
    public virtual void DoSomething()
    {
    Console.WriteLine("Base imp");
    }
    }
    public class MyDerivedClass : MyBaseClass
    {
    new public void DoSomething()
    {
    Console.WriteLine("Derived imp");
    }
    }

     无论是重写成员还是隐藏成员,都可以在派生类的内部访问基类成员。这在许多情况下都是很
    有用的,例如:
    1 要对派生类的用户隐藏继承的公共成员,但仍能在类中访问其功能。
     2要给继承的虚拟成员添加实现代码,而不是简单地用重写的新执行代码替换它。
    为此,可以使用 base 关键字,它表示包含在派生类中的基类的实现代码(在控制构造函数时,
    其用法是类似的,如第9 所述),例如:
    public class MyBaseClass
    {
    public virtual void DoSomething()
    {
    // Base implementation.
    }
    }
    public class MyDerivedClass : MyBaseClass
    {
    public override void DoSomething()
    {
    // Derived class implementation, extends base class implementation.
    base.DoSomething();
    // More derived class implementation.
    }
    }
    这段代码执行包含在 MyBaseClass 中的 DoSomething()版本,MyBaseClass 是 MyDerivedClass
    的基类,而DoSomething()版本包含在MyDerivedClass 中。因为base 使用的是对象实例,所以在静
    态成员中使用它会产生错误。

    而另外一个关键字this则是在当前对象的实例,(直接上例子啦)

    public void doSomething()
    {
    MyTargetClass myObj = new MyTargetClass();
    myObj.DoSomethingWith(this);
    }

    ******************************************华丽丽的分割线你懂得!

    而this最常用的是如下的代码

    this 关键字的另一个常见用法是限定本地类型的成员,例如:
    public class MyClass
    {
    private int someData;
    public int SomeData
    {
    get
    {
    return this.someData;
    }
    }
    }
    许多开发人员都喜欢这个语法,它可以用于任意成员类型,因为可以一眼看出引用的是成员,
    而不是局部变量。

  • 相关阅读:
    使用C#中的DirectorySearcher来获得活动目录中的组织结构与用户等信息,并在展示成树形结构(附源代码)
    oracle的简单操作和要注意的地方
    lambda匿名函数
    Linux查看系统信息(版本、cpu、raid)
    chmod 777后,目录权限不可写解决方法
    linux /boot空间满了如何清理
    k3s
    IDEA项目编译参数Werror设置
    minicube 安装
    ubuntu安装docker
  • 原文地址:https://www.cnblogs.com/mamiyiya777/p/5826322.html
Copyright © 2020-2023  润新知