c#方法重写和隐藏的学习示例
时间:2022-12-24 14:20:12
最近正在学习c#,对其中的方法重写和隐藏的概念很是模糊,现在将其归纳如下:
1:方法重写:就是在基类中的方法用virtual关键字来标识,然后在继承类中对该类进行重写(override),这样基类中的方法已经被重写了,已经失去了功能了。当让基类的对象的引用直接指向继承类的对象时(多态性),调用该方法则是调用的继承类的方法。
2:方法隐藏:无论基类中的方法是否用了virtual关键字,继承类中都可以用new关键字(如果不用new的话,不会产生错误,但会生成一个编译警告)将基类中的方法隐藏,所谓隐藏就是隐藏,不像重写,重写就是原来的(基类中)已经不存在了,而隐藏是原来的还存在。所以当让基类的对象的引用直接指向继承类的对象时(多态性),调用该方法则是调用的基类的方法。
代码如下:
public class BaseClass
{
public void functionA()
{
Console.WriteLine("BaseFunctionA https://www.jb51.net/sosoft/");
}
public virtual void functionB()
{
Console.WriteLine("BaseFunctionB https://www.jb51.net/sosoft/");
}
}
public class DerivedClass:BaseClass
{
public new void functionA()
{
Console.WriteLine("DerivedFunctionA https://www.jb51.net/sosoft/");
}
public override void functionB()
{
Console.WriteLine("DerivedFunctionB https://www.jb51.net/sosoft/");
}
}
当利用多态性执行下面代码时:
BaseClass baseFunction=new DerivedClass();
baseFunction.functionA();
baseFunction.functionB();
得到的结果是:
BaseFunctionA https://www.jb51.net/sosoft/
DerivedFunctionB https://www.jb51.net/sosoft/
标签:方法重写
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring Boot 集成Elasticsearch模块实现简单查询功能
2022-09-05 06:31:31
深入分析Android ViewStub的应用详解
2022-09-14 16:50:19
![](https://img.aspxhome.com/file/2023/7/130417_0s.gif)
基于C#实现简单离线注册码生成与验证
2022-02-08 15:22:49
JVM垃圾收集器详解
2022-10-06 10:46:00
![](https://img.aspxhome.com/file/2023/8/78938_0s.png)
springboot+springsecurity如何实现动态url细粒度权限认证
2023-10-01 04:06:39
![](https://img.aspxhome.com/file/2023/0/64130_0s.png)
springboot+thymeleaf 文件上传功能的实现代码
2023-11-25 05:08:59
![](https://img.aspxhome.com/file/2023/3/60053_0s.png)
分享几个Java工作中实用的代码优化技巧
2023-11-28 12:04:50
![](https://img.aspxhome.com/file/2023/0/59890_0s.webp)
java 实现比较版本号功能
2022-08-12 20:35:11
eclipse 如何创建 user library 方法详解
2021-12-29 00:33:56
![](https://img.aspxhome.com/file/2023/7/113417_0s.png)
Spring-boot的debug调试代码实例
2023-10-17 04:49:01
基于Nacos实现Spring Cloud Gateway实现动态路由的方法
2022-04-14 07:18:56
![](https://img.aspxhome.com/file/2023/3/122293_0s.png)
Java去重排序之Comparable与Comparator的使用及说明
2023-04-28 00:49:27
![](https://img.aspxhome.com/file/2023/8/122278_0s.png)
JAVA实现心跳检测(长连接)
2022-12-16 04:26:30
![](https://img.aspxhome.com/file/2023/6/81246_0s.jpg)
java实现图片裁切的工具类实例
2021-06-29 14:45:58
详解spring注解式参数校验
2023-05-08 15:28:52
Java swing实现支持录音等功能的钢琴程序
2022-08-21 12:30:16
![](https://img.aspxhome.com/file/2023/1/80951_0s.jpg)
详解Java中的日期类
2022-08-27 17:14:03
浅谈Java多进程程序的运行模式
2021-07-06 11:06:49
Java/Web调用Hadoop进行MapReduce示例代码
2023-09-01 05:05:50
![](https://img.aspxhome.com/file/2023/3/77093_0s.png)
java两个integer数据判断相等用==还是equals
2021-06-14 00:46:52