C#学习相关系列之base和this的常用方法

news2024/10/5 23:26:22

一、base的用法

        Base的用法使用场景主要可以概括为两种:

        1 、访问基类方法

        2、 调用基类构造函数

        使用要求:仅允许用于访问基类的构造函数、实例方法或实例属性访问器。从静态方法中使用 base 关键字是错误的所访问的基类是类声明中指定的基类。 例如,如果指定 class ClassB : ClassA,则从 ClassB 访问 ClassA 的成员,而不考虑 ClassA 的基类。

例子1、访问基类方法

    public class animal
    {
        public virtual void sound()
        {
            Console.WriteLine("动物的叫声:wowowow");
        }
    
    }
    public class dog:animal
    {
        public override void sound()
        {
            base.sound();
            Console.WriteLine("dog:wowowowo");
        }

    }

    static void Main(string[] args)
    {
        dog dog = new dog();
        dog.sound();
        Console.ReadKey();
    }

        基类 Person 和派生类 Employee 都有一个名为 Getinfo 的方法。 通过使用 base 关键字,可以从派生类中调用基类的 Getinfo 方法。

运行结果为:

例子2、调用基类构造函数

    public class animal
    {
        public animal()
        {
            Console.WriteLine("发现未知动物");
        }
        public animal(int a)
        {
            Console.WriteLine("发现{0}只未知动物",a);
        }
        public virtual void sound()
        {
            Console.WriteLine("动物的叫声:wowowow");
        }
    
    }
    public class dog:animal
    {
        public dog() : base()
        {
            Console.WriteLine("未知动物为小狗");
        }
        public dog(int a) : base(a)
        {
            Console.WriteLine("小狗的数量为{0}",a);
        }
        public override void sound()
        {
            base.sound();
            Console.WriteLine("dog:wowowowo");
        }

    }


        class Program
    {
        static void Main(string[] args)
        {
            dog dog = new dog(2);
            dog.sound();
            Console.ReadKey();
        }
    }

运行结果为:

 

从例子中我们也可以看的出对于继承类的构造函数,访问顺序是父类构造函数,再访问子类的构造函数。base 用于用户父类构造函数,this 用于调用自己的构造函数。)

二、this的用法

      this的用法主要总结为5种:

  1. 限定类似名称隐藏的成员
  2. 将对象作为参数传递给方法
  3. 声明索引器
  4. 串联构造函数
  5. 扩展方法

1、限定类似名称隐藏的成员(用 this 区别类成员和参数)

public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        // Use this to qualify the members of the class
        // instead of the constructor parameters.
        this.name = name;
        this.alias = alias;
    }
}

 2、将对象作为参数传递给方法

    public class animal
    {
        public void leg_count(dog dog)
        {
            Console.WriteLine("狗腿的数量为:"+dog.leg);
        }
        public void leg_count(duck duck)
        {
            Console.WriteLine("鸡腿的数量为:" + duck.leg);
        }
    }
    public class dog
    {
        public int leg = 4;
        public animal animal;
        public void count()
        {
            animal = new animal();
            animal.leg_count(this);
        }

    }
    public class duck
    {
        public int leg = 2;
        public animal animal;
        public void count()
        {
            animal = new animal();
            animal.leg_count(this);
        }

    }

    
        static void Main(string[] args)
        {
            dog dog = new dog();
            duck duck = new duck();
            dog.count();
            duck.count();
            Console.ReadKey();
        }

运行结果为:

 

3、声明索引器

索引器类似于属性。 很多时候,创建索引器与创建属性所使用的编程语言特性是一样的。 索引器使属性可以被索引:使用一个或多个参数引用的属性。 这些参数为某些值集合提供索引。

使用 this 关键字作为属性名声明索引器,并在方括号内声明参数。

namespace ConsoleApp1
{
    public class IndexExample
    {
        private string[] nameList = new string[10];
        public string this[int index]
        {
            get { return nameList[index]; }
            set { nameList[index] = value; }
        }
        public int this[string name]
        {
            get
            {
                for(int i = 0; i < nameList.Length; i++)
                {
                    if(nameList[i] == name) return i;
                }
                return -1;
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            IndexExample indexExample = new IndexExample();
            indexExample[0] = "Tom";
            indexExample[1] = "Lydia";
            Console.WriteLine("indexExample[0]: " + indexExample[0]);
            Console.WriteLine("indexExample['Lydia']: "+ indexExample["Lydia"]);
        }
    }
}

运行结果为:

4、串联构造函数

namespace ConsoleApp1
{
    public class Test
    {
        public Test()
        {
            Console.WriteLine("no parameter");
        }
        public Test(string str) : this()
        {
            Console.WriteLine("one parameter: " + str);
        }

        public Test(string str1, string str2): this(str1)
        {
            Console.WriteLine("two parameters: " + str1 + " ; " + str2);
        }
    }

    public class ProgramTest
        {
        static void Main(string[] args)
        {
            Console.WriteLine("Test t1 = new Test();");
            Test t1 = new Test();
            Console.WriteLine("Test t2 = new Test('str1');");
            Test t2 = new Test("str1");
            Console.WriteLine("Test t3 = new Test('str2', 'str3');");
            Test t3 = new Test("str2", "str3");
        }
        }
}

运行结果为:

Test t1 = new Test();
no parameter
Test t2 = new Test('str1');
no parameter
one parameter: str1
Test t3 = new Test('str2', 'str3');
no parameter
one parameter: str2
two parameters: str2 ; str3

 5、扩展方法

  • 定义包含扩展方法的类必须为静态类
  • 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
  • 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
  • 在调用代码中,添加 using 指令,用于指定包含扩展方法类的 using。
  • 和调用类型的实例方法那样调用这些方法。

官方示例:

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    // Extension methods must be defined in a static class.
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this string str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    // Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            // Call the method as if it were an
            // instance method on the type. Note that the first
            // parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

 自己自定义类的代码:

第一步、新建一个扩展类

第二步、对扩展类定义

扩展类要引用被扩展类的命名空间。

第三步、在使用界面内引入扩展类的命名空间

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using classextension;

namespace 符号测试
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            test.method();
            test.methodextension();
            Console.ReadKey();
        }
    }
    public class Test
    {
        public void method()
        {
            Console.WriteLine("这是原始类内的方法");
        }
    }

}


扩展类/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 符号测试;

namespace classextension
{
    public  static class TestExtension
    {
        public static void methodextension(this Test test)
        {
            Console.WriteLine("这是扩展类的方法");
        }
    }
}

运行结果为:

参考文献:

C# - base 关键字用法_c#中base的用法-CSDN博客

C# - this 的用法_c# 静态函数 子类this参数_wumingxiaoyao的博客-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1248039.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Latex 基本操作

好久没写博客了&#xff0c;最近一直在写毕业论文&#xff0c;不过对 Latex 的使用进一步了解&#xff0c;这里整理下来方便小伙伴们学习和参考。可以在 Gituhub 上找自己学校的模板&#xff0c;通常我们都是在找到的模板上进行写作&#xff0c;只需要掌握一下基本操作&#xf…

生物动力葡萄酒和有机葡萄酒一样吗?

农业维持了数十万年的文明&#xff0c;但当人类以错误的方式过多干预&#xff0c;过于专注于制造和操纵产品时&#xff0c;农业往往会失败。如果我们的目标是获得最高质量的收成&#xff0c;并长期坚持我们的做法&#xff0c;我们就必须与土地打交道。 当我们开始寻找生物动力…

Java Web——XML

1. XML概述 XML是EXtensible Markup Language的缩写&#xff0c;翻译过来就是可扩展标记语言。XML是一种用于存储和传输数据的语言&#xff0c;它使用标签来标记数据&#xff0c;以便于计算机处理和我们人来阅读。 “可扩展”三个字表明XML可以根据需要进行扩展和定制。这意味…

红队攻防实战之从边界突破到漫游内网(无cs和msf)

也许有一天我们再相逢&#xff0c;睁大眼睛看清楚&#xff0c;我才是英雄。 本文首发于先知社区&#xff0c;原创作者即是本人 本篇文章目录 网络拓扑图&#xff1a; 本次红队攻防实战所需绘制的拓扑图如下&#xff1a; 边界突破 访问网站&#xff1a; http://xxx.xxx.xxx…

Java之异常(下):自定义异常类

一、前言&#xff1a; 在我前面写的博客文章里有一篇叫《Java中关于自定义异常类的一些问题》&#xff0c;它里面讲到了大部分关于自定义异常的基础知识&#xff0c;如果大家想了解底层可以去那里查看。今天我将用一次细节的案例解析&#xff1a;我们所说的自定义异常类。 二、…

【学习篇】Linux中grep、sed、awk

Linux 文本处理三剑客 – awk, sed, grep grep过滤文本 https://zhuanlan.zhihu.com/p/561445240 grep 是 Linux/Unix 系统中的一个命令行工具&#xff0c;用于从文件中搜索文本或字符串。grep 代表全局正则表达式打印。当我们使用指定字符串运行 grep 命令时&#xff0c;如…

VMware安装windows操作系统

一、下载镜像包 地址&#xff1a;镜像包地址。 找到需要的版本下载镜像包。 二、安装 打开VMware新建虚拟机&#xff0c;选择用镜像文件。将下载的镜像包加载进去即可。

(Matalb回归预测)GA-BP遗传算法优化BP神经网络的多维回归预测

目录 一、程序及算法内容介绍&#xff1a; 基本内容&#xff1a; 亮点与优势&#xff1a; 二、实际运行效果&#xff1a; 三、部分代码&#xff1a; 四、分享本文全部代码数据说明手册&#xff1a; 一、程序及算法内容介绍&#xff1a; 基本内容&#xff1a; 本代码基于M…

如何在 Web 应用程序中查找端点?

如何在 Web 应用程序中查找端点? 这篇文章主要讲述了如何在网络应用中找到端点。以下是文章的主要要点: 端点是网络服务的访问地址,通过引用这个URL,客户可以访问服务提供的操作。端点提供了寻址Web服务端点所需的信息。 HTTP消息是服务器和客户端之间交换数据的方式,包…

2023年c语言程序设计大赛

7-1 这是一道送分题 为了让更多的同学参与程序设计中来&#xff0c;这里给同学们一个送分题&#xff0c;让各位感受一下程序设计的魅力&#xff0c;并祝贺各位同学在本次比赛中取得好成绩。 注&#xff1a;各位同学只需将输入样例里的代码复制到右侧编译器&#xff0c;然后直…

电子作业指导书系统如何提高作业人员的培训效率和作业规范

在现代制造业中&#xff0c;提高生产效率和产品质量是企业不断追求的目标。而对于车间员工来说&#xff0c;如何提高生产培训效率和作业规范是一个重要的问题。电子作业指导书系统作为一种新型的生产管理工具&#xff0c;可以有效提高车间员工的生产培训效率和作业规范。本文将…

maven 将Jar包安装到本地仓库

window系统&#xff1a; 注意事项&#xff1a;在windows中&#xff0c;使用mvn指令将jar安装到本地仓库时&#xff0c;一定要将相关资源使用“"”包裹上&#xff0c;不然会报下面的错&#xff1a; mvn install:install-file "-DfileD:\BaiduNetdiskDownload\qianzixi…

全球服的游戏服务器架构设计

全球服的游戏服务器架构设计 版权声明 本文为“优梦创客”原创文章&#xff0c;您可以自由转载&#xff0c;但必须加入完整的版权声明 文章内容不得删减、修改、演绎 相关学习资料见文末 主题 常见服务器端架构划分 不同类型游戏的架构选择与瓶颈 如何设计通用、可伸缩的…

python 爬百度热搜并生成词云

1、爬取百度body存入txt def get_baidu_hot():url "https://top.baidu.com/board?tabrealtime"headers {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3&…

定制手机套餐---python序列

if __name__ __main__:print("定制手机套餐")print("")#定义电话时长&#xff1a;字典callTimeOptions{1:0分钟,2:50分钟,3:100分钟,4:300分钟,5:不限量}keyinput("请输入电话时长的选择编号&#xff1a;")valuecallTimeOptions.get(key)if val…

看完就会,从抓包到接口测试的全过程解析【1500字保姆级教程】

一、为什么抓包 1、从功能测试角度 通过抓包查看隐藏字段 Web 表单中会有很多隐藏的字段&#xff0c;这些隐藏字段一般都有一些特殊的用途&#xff0c;比如收集用户的数据&#xff0c;预防 CRSF 攻击&#xff0c;防网络爬虫&#xff0c;以及一些其他用途。这些隐藏字段在界面…

中国上市公司漂绿程度及其同构指数(多种测算方法,2012-2022年)

数据简介&#xff1a;20 世纪 90 年代开始&#xff0c;国际上关于绿色市场和绿色管理的学术文献日渐丰富&#xff0c;众多企业积极响应碳排放政策的号召&#xff0c;但其中有多少企业是实实在在的进行碳减排技术创新&#xff0c;又有多少企业打着绿色低碳行为的口号来吸引眼球、…

举个栗子!Quick BI 技巧(4):创建面积图

面积图又叫区域图&#xff0c;是在折线图的基础之上形成的, 它将折线图中折线与自变量坐标轴之间的区域使用颜色或者纹理填充&#xff0c;这样一个填充区域我们叫做面积&#xff0c;颜色的填充也可以更好的突出趋势信息。 有数据粉好奇如何使用 Quick BI 来制作面积图&#xf…

CAD图纸管理软件是否支持自定义属性?

CAD图纸管理软件是否支持自定义属性&#xff1f; 彩虹图纸管理软件_图纸管理系统_图纸文档管理软件系统_彩虹EDM【官网】 CAD图纸管理软件 是一种专业用于管理CAD图纸的工具&#xff0c;它可以帮助用户更加方便地管理、分类和检索自己的CAD图纸。在这个软件中&#xff0c;自定…

沃趣班11月月考题目解析

沃趣班11月月考题目解析 1.在oracle中创建用户时&#xff0c;若未设置default tablespace关键字&#xff0c;则oracle将哪个表空间分配给用户作为默认表空间 答案&#xff1a;D.user SQL> create user mytest identified by 123456; SQL> grant connect to mytest; SQL…