概述
this在C#中有多种用法,也比较常见,这节主要针对它常用的四种用法展开讲解.
用法1:构造函数串联执行;
用法2:通过this区分传参和类中全局的定义;
用法3:方法扩展类;
用法4:将对象作为参数传递;
代码实例
using System.Text;namespace Caliburn.Micro.Hello.ViewModels
{public class ThisUsageViewModel : Screen, IViewModel{private StringBuilder stringBuilder = new StringBuilder();public string DisplayInfo { get; set; }public ThisUsageViewModel(){DisplayName = "ThisUsageViewModel";DisplayInfo = "【1】this is ctor one";stringBuilder.AppendLine(DisplayInfo);DisplayInfo = "【2】this is ctor two";stringBuilder.AppendLine(DisplayInfo);DisplayInfo = "【3】this is CallMember";CallMember(DisplayInfo);stringBuilder.AppendLine(TestHelper.ObjectTransfer(this));//用法4:将对象作为参数传递DisplayInfo = stringBuilder.ToString();}/// <summary>/// 用法1:构造函数串联执行/// </summary>/// <param name="flag"></param>public ThisUsageViewModel(bool flag) : this(){}public void CallMember(string DisplayInfo){this.DisplayInfo = DisplayInfo;//用法2:通过this区分传参和类中全局的定义stringBuilder.AppendLine(this.DisplayInfo);this.ExtensionMethod();}public void ExtensionMethod(){double aHeight = 175;double bHeight = 1.82;stringBuilder.AppendLine($"【4】{aHeight.CMToM()}");stringBuilder.AppendLine($"【5】{bHeight.MToCM()}");}}/// <summary>/// 用法3:方法扩展类/// </summary>public static class DoubleExtension{public static double MToCM(this double value){return value * 100;}public static double CMToM(this double value){return value / 100;}}public class TestHelper{public static string ObjectTransfer(ThisUsageViewModel thisUsageView){thisUsageView.DisplayInfo = "【6】this is Object Transfer";return thisUsageView.DisplayInfo;}}
}
运行结果:
用法讲解:1. 串联构造函数
构造函数通过继承this(),新的构造函数执行时候会先执行类中默认的无参构造函数然后再执行新的构造函数;比如本实例中,如果实例化了一个类:
var thisUsageViewModel = new ThisUsageViewModel(true);
这个类会先执行ThisUsageViewModel()中的代码,再执行ThisUsageViewModel(bool flag) : this()里的代码;
用法讲解:2. 通过this区分传参和类中全局的定义
通过加前缀this代表调用的是类中的全局变量、属性或者方法,尤其是方法的传参和类中的变量名一致时,需要通过this区分;
用法讲解:3. 方法扩展类
如本实例的类DoubleExtension,中的MToCM和CMToM,第一个参数用this标注代表是要扩展的类型,然后类和方法都需要是公共的静态类型,这种我们就可以通过double.MToCM()或double.CMToM去调用扩展方法;
用法讲解:4. 将对象作为参数传递
如本实例的
stringBuilder.AppendLine(TestHelper.ObjectTransfer(this));//用法4:将对象作为参数传递
this实际上就是实例化了一个对象作为参数进行传递.
源码下载
链接:https://pan.baidu.com/s/1RAMFfy-Kjb01f7PUevP_7w
提取码:6666