C#学习 - 关于this的几种用法

C#中,this 关键字的几种用法

1. 用this来区分参数和成员名

        public class Person
        {
            public enum SEX { MALE, FEMALE };
            public string Name { get; set; }
            public SEX Sex { get; set; }

            public Person(string Name, SEX Sex)
            {
                this.Name = Name;
                this.Sex = Sex;
            }
        }

2. 用this来将一个object作为参数传递

       public class Person2
        {
            public enum SEX { MALE, FEMALE };

            public string Name { get; set; }
            public SEX Sex { get; set; }

            public Person2(string Name, SEX Sex)
            {
                this.Name = Name;
                this.Sex = Sex;
            }
            public void ShowName()
            {
                Helper.PrintName(this);
            }
        }

3. 用this来声明indexer

       public class Person3
        {
            public Dictionary<string, string> Friend;
            public enum SEX { MALE, FEMALE };

            public string Name { get; set; }
            public SEX Sex { get; set; }

            public Person3(string Name, SEX Sex)
            {
                this.Name = Name;
                this.Sex = Sex;
                Friend = new Dictionary<string, string>();
            }
            public void ShowName()
            {
                Helper.PrintName(this);
            }
            public string this[string key]
            {
                get
                {
                    return Friend[key];
                }
                set
                {
                    if (!Friend.ContainsKey(key))
                        Friend.Add(key, value);
                }
            }
        }
 
      Person3 p = new Person3("Tom", Person3.SEX.MALE);
            p["Tom"] = "Jerry";
            p["Jerry"] = "Tom";

4. 用this来定义类扩展函数

    public interface IFoo
    {
        int Marker { get; set; }
    }

    public static class FooExtentions
    {
        public static void NextMarker(this IFoo thing) => thing.Marker += 1;
    }
    
    public class MyType : IFoo
    {
        public int Marker { get; set; }
    }

    ...

    IFoo l3_a = new MyType { Marker = 4 };
    l3_a.NextMarker();

5. 用this来调用不同签名的构造函数

public class Foo
{
  Foo(int x, int y)
  {
     this.x = x;
     this.y = y;
  }

  Foo(int x) : this(x, 10) {}  // y defaults to 10
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值