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

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

一、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("这是扩展类的方法");
        }
    }
}

运行结果为:


相关文章
|
6天前
|
开发框架 .NET 程序员
C# 去掉字符串最后一个字符的 4 种方法
在实际业务中,我们经常会遇到在循环中拼接字符串的场景,循环结束之后拼接得到的字符串的最后一个字符往往需要去掉,看看 C# 提供了哪4种方法可以高效去掉字符串的最后一个字符
|
25天前
|
C#
C#一分钟浅谈:Lambda 表达式和匿名方法
本文详细介绍了C#编程中的Lambda表达式与匿名方法,两者均可用于定义无名函数,使代码更简洁易维护。文章通过基础概念讲解和示例对比,展示了各自语法特点,如Lambda表达式的`(parameters) =&gt; expression`形式及匿名方法的`delegate(parameters)`结构。并通过实例演示了两者的应用差异,强调了在使用Lambda时应注意闭包问题及其解决策略,推荐优先使用Lambda表达式以增强代码可读性。
26 8
|
25天前
|
Linux C# 开发者
Uno Platform 驱动的跨平台应用开发:从零开始的全方位资源指南与定制化学习路径规划,助您轻松上手并精通 C# 与 XAML 编程技巧,打造高效多端一致用户体验的移动与桌面应用程序
【9月更文挑战第8天】Uno Platform 的社区资源与学习路径推荐旨在为初学者和开发者提供全面指南,涵盖官方文档、GitHub 仓库及社区支持,助您掌握使用 C# 和 XAML 创建跨平台原生 UI 的技能。从官网入门教程到进阶技巧,再到活跃社区如 Discord,本指南带领您逐步深入了解 Uno Platform,并提供实用示例代码,帮助您在 Windows、iOS、Android、macOS、Linux 和 WebAssembly 等平台上高效开发。建议先熟悉 C# 和 XAML 基础,然后实践官方教程,研究 GitHub 示例项目,并积极参与社区讨论,不断提升技能。
35 2
|
2月前
|
图形学 C# 开发者
全面掌握Unity游戏开发核心技术:C#脚本编程从入门到精通——详解生命周期方法、事件处理与面向对象设计,助你打造高效稳定的互动娱乐体验
【8月更文挑战第31天】Unity 是一款强大的游戏开发平台,支持多种编程语言,其中 C# 最为常用。本文介绍 C# 在 Unity 中的应用,涵盖脚本生命周期、常用函数、事件处理及面向对象编程等核心概念。通过具体示例,展示如何编写有效的 C# 脚本,包括 Start、Update 和 LateUpdate 等生命周期方法,以及碰撞检测和类继承等高级技巧,帮助开发者掌握 Unity 脚本编程基础,提升游戏开发效率。
40 0
|
2月前
|
C#
C# async await 异步执行方法
C# async await 异步执行方法
41 0
|
2月前
|
C# 图形学
小功能⭐️C#控制小数点后位数的方法
小功能⭐️C#控制小数点后位数的方法
|
2月前
|
开发框架 .NET API
C#/.NET/.NET Core推荐学习书籍(24年8月更新)
C#/.NET/.NET Core推荐学习书籍(24年8月更新)
|
2月前
|
C#
WPF/C#:数据绑定到方法
WPF/C#:数据绑定到方法
32 0
|
5月前
|
开发框架 前端开发 .NET
C#编程与Web开发
【4月更文挑战第21天】本文探讨了C#在Web开发中的应用,包括使用ASP.NET框架、MVC模式、Web API和Entity Framework。C#作为.NET框架的主要语言,结合这些工具,能创建动态、高效的Web应用。实际案例涉及企业级应用、电子商务和社交媒体平台。尽管面临竞争和挑战,但C#在Web开发领域的前景将持续拓展。
168 3
|
5月前
|
SQL 开发框架 安全
C#编程与多线程处理
【4月更文挑战第21天】探索C#多线程处理,提升程序性能与响应性。了解C#中的Thread、Task类及Async/Await关键字,掌握线程同步与安全,实践并发计算、网络服务及UI优化。跟随未来发展趋势,利用C#打造高效应用。
181 3