C# 基础拾忆 (二)

44 阅读4分钟

this 关键字的三种用法 1

用法1

this 代表当前类的实例对象

当我们定义了一个类的全局变量时 而该类方法中也声明了 相同的参数名 时 如何区分两个相同参数名称的调用 使用 this 以更直观地看到 this.参数名 为全局参数。

首先声明一个类

 public class TestThisClass
    {
        //用法一 this 代表当前类的实例对象
        private string scope = "全局变量";
        public string getResult()
        {
            string scope = "局部变量";
            // this 代表 TestThisClass 的实例对象
            // 所以 this.scope 对应的是全局变量
            // scope 对应的是 getResult 方法内的局部变量
            return this.scope + "-" + scope;
        }
    }

我在 main 函数中使用

 public static void Main(string[] args)
{

            //用法一 this 代表当前类的实例对象
            TestThisClass testThisClass = new TestThisClass();
            Console.WriteLine(testThisClass.getResult());

}

输出结果

注意 是先全局变量再局部变量

用法2

this 串联构造函数 (:this() 方法) 目的是为了实例化该类时 还会先 自动调用 一次 base() 中对应参数的方法类 再继续执行原本的方法

首先声明一个类

    public class TsetThisCLClass
    {
        public TsetThisCLClass()
        {
            Console.WriteLine("无参构造函数");
        }
        // this() 对应有两个参构造方法 TsetThisCLClass(string text, string text2)
        // 先执行 TsetThisCLClass(string text, string text2),
        // 后执行 TsetThisCLClass(string text)
        public TsetThisCLClass(string text) : this("李四", text)
        {
            Console.WriteLine(text);
            Console.WriteLine("有参构造函数");
        }

        public TsetThisCLClass(string text, string text2)
        {
            Console.WriteLine(text + text2);
            Console.WriteLine("有两个参数的参构造函数");
        }
    }

我在 main 函数中使用

// 用法二  用this串联构造函数  (:base() 方法)
TsetThisCLClass test = new TsetThisCLClass("张三");

输出结果

注意 是先输出 base 中带两个参数的方法 再输出本身

用法3

为原始类型扩展方法 主要是用来我们平时经常用到的类型 (stringobject

首先声明一个扩展类

  public static class Extends
    {
        // string 类型扩展 ToJson 方法
        public static object stringToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        
        // object 类型扩展 ToJson 方法
        public static string objectToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
    }

具体调用

object a = "asjfh";
string b = "afsdd";
a.objectToJson(); // 这里的 a 是 object 类型 他可直接调用扩展方法 this object 方法中声明的内容 
b.stringToJson(); // 这里的 b 是 string 类型 他可直接调用扩展方法 this string 方法中声明的内容

举个例子

.net core 注入配置文件 使用 this 方法

        public void ConfigureServices(IServiceCollection services)
        {
                var builder = new ConfigurationBuilder();
                builder.AddJsonFile($"{AppDomain.CurrentDomain.BaseDirectory}/A.json", false, true);
                var config = builder.Build();
                services.AddAlhgInfoConf(config);// 调用下面的方法 
        }

再声明一个(扩展)方法

         //这里的方法 声明了参数 this IServiceCollection services 所以上面的 services 可以直接调用 AddAlhgInfoConf 该方法 这是属于 this 的扩展方法
        public static IServiceCollection AddAlhgInfoConf(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<AlhgInfoConf>(configuration);
            return services;
        }

C# 参考之访问关键字:base、this2

base 关键字用于从派生类中访问基类的成员: 

  • 调用基类上已被其他方法重写的方法。 
  • 指定创建派生类实例时应调用的基类构造函数。 
  • 基类访问只能在构造函数、实例方法或实例属性访问器中进行。 

base 示例

在派生类中调用基类方法

// base 关键字  
// 访问基类成员  
using System;  
  
public class BaseClass  
{  
    protected string _className = "BaseClass";  
  
    public virtual void PrintName()  
    {  
        Console.WriteLine("Class Name: {0}", _className);  
    }  
}  
  
class DerivedClass : BaseClass  
{  
    public string _className = "DerivedClass";  
  
    public override void PrintName()  
    {  
        Console.Write("The BaseClass Name is {0}");  
        //调用基类方法  
        base.PrintName();  
        Console.WriteLine("This DerivedClass is {0}", _className);  
    }  
}  
  
class TestApp  
{  
    public static void Main()  
    {  
        DerivedClass dc = new DerivedClass();  
        dc.PrintName();  
    }  
}

控制台输出:

The BaseClass Name is BaseClass
This DerivedClass is DerivedClass

在派生类中调用基类构造函数

// keywords_base2.cs  
using System;  
public class BaseClass  
{  
    int num;  
  
    public BaseClass()  
    {  
        Console.WriteLine("in BaseClass()");  
    }  
  
    public BaseClass(int i)  
    {  
        num = i;  
        Console.WriteLine("in BaseClass(int {0})", num);  
    }  
}  
  
public class DerivedClass : BaseClass  
{  
    // 该构造器调用 BaseClass.BaseClass()  
    public DerivedClass() : base()  
    {  
    }  
  
    // 该构造器调用 BaseClass.BaseClass(int i)  
    public DerivedClass(int i) : base(i)  
    {  
    }  
  
    static void Main()  
    {  
        DerivedClass dc = new DerivedClass();  
        DerivedClass dc1 = new DerivedClass(1);  
    }  
}

控制台输出:

in BaseClass()
in BaseClass(1)

注意点

静态方法 中使用 base 关键字是 错误 的。 


this 关键字引用类的当前实例。

以下是 this 的常用用途:

  • 限定被相似的名称隐藏的成员 
  • 将对象作为参数传递到其他方法 
  • 声明索引器

由于 静态成员函数 存在于类一级,并且不是对象的一部分,因此没有 this 指针。在 静态方法 中引用 this错误 的。

索引器 允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。

this 示例

综合示例

// this 关键字  
// keywords_this.cs  
using System;  
class Employee  
{  
    private string _name;  
    private int _age;  
    private string[] _arr = new string[5];  
  
    public Employee(string name, int age)  
    {  
        // 使用this限定字段,name与age  
        this._name = name;  
        this._age = age;  
    }  
  
    public string Name  
    {  
        get { return this._name; }  
    }  
  
    public int Age  
    {  
        get { return this._age; }  
    }  
  
    // 打印雇员资料  
    public void PrintEmployee()  
    {  
        // 将 Employee 对象作为参数传递到 DoPrint 方法  
        Print.DoPrint(this);  
    }  
  
    /// @note 声明索引器  
    public string this[int param]  
    {  
        get { return _arr[param]; }  
        set { _arr[param] = value; }  
    }  
  
}  

class Print  
{  
    public static void DoPrint(Employee e)  
    {  
        Console.WriteLine("Name: {0}\nAge: {1}", e.Name, e.Age);  
    }  
}  
  
class TestApp  
{  
    static void Main()  
    {  
        Employee E = new Employee("Hunts"21);  
        E[0] = "Scott";  
        E[1] = "Leigh";  
        E[4] = "Kiwis";  
        E.PrintEmployee();  
  
        for(int i=0; i<5; i++)  
        {  
            Console.WriteLine("Friends Name: {0}", E[i]);  
        }  
  
        Console.ReadLine();  
    }  
}

控制台输出:

Name: Hunts
Age: 21
Friends Name: Scott
Friends Name: Leigh
Friends Name: 
Friends Name: 
Friends Name: Kiwis

Footnotes

  1. C# this关键字的三种用法

  2. C# 参考之访问关键字:base、this