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
}