C# 关键字this用法

1.this代表当前类的实例对象

public class Test
{
    public string Name{get;set;}      
    public void TestChange(string strName)
    {
        this.Name=strName;
    }
}

2.搭配构造函数:a.直接当成参数传递  b.构造函数执行顺序

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

3.类的索引器:参数可以是int,也可以是string等其他类型

public class Test
{
    public string Name{get;set;}
    //索引器  []括号里面可以是string,int,array等
    public string this[string index]
    {    
        if(index=="xxx")
        {
            return "xxx";
        }
        else
        {
            return "ccc";
        }
    }    
}            

4.类的扩展方法;注意:类必须是静态,方法也是静态,格式如下

public static class Test
{
    //this 放在参数前,且该方法对应string
    //改变参数类型就可以应对其他类型
    public static string ExpandString(this string name)
    {
        return name+name;
    }
}

 

posted @ 2019-01-22 09:49  木狼  阅读(4201)  评论(0编辑  收藏  举报