在c#中,this
关键字有以下几种主要作用:
引用当前对象:this
用于引用当前类的实例。可以通过 this
关键字来访问当前对象的成员变量、方法和属性。
class myclass { private int myvar; public void setvar(int var) { this.myvar = var; // 使用 this 关键字引用当前对象的成员变量 } }
区分字段与局部变量:当成员变量和局部变量同名时,可以使用 this
关键字来区分。
class myclass { private int myvar; public void setvar(int myvar) { this.myvar = myvar; // 使用 this 关键字指定成员变量 } }
在构造函数中调用其他构造函数:可以使用 this
关键字来调用同一个类中的其他构造函数。
class myclass { private int myvar; public myclass(int var) { this.myvar = var; } public myclass() : this(0) // 调用另一个构造函数 { } }
传递当前对象给其他方法或构造函数:可以使用 this
关键字将当前对象作为参数传递给其他方法或构造函数。
class myclass { public void method() { anotherclass.dosomething(this); // 将当前对象传递给另一个方法 } }
使用this添加扩展方法
using system; public static class stringextensions { public static int wordcount(this string str) { return str.split(new char[] { ' ', '.', '?' }, stringsplitoptions.removeemptyentries).length; } } class program { static void main() { string sentence = "hello, world! this is a sentence."; int wordcount = sentence.wordcount(); console.writeline($"the sentence has {wordcount} words."); } }
总的来说,this
关键字在c#中主要用于引用当前对象,区分字段与局部变量,调用其他构造函数以及传递当前对象给其他方法或构造函数
到此这篇关于c# this关键字的作用的文章就介绍到这了,更多相关c# this关键字内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论