C#中的this关键字

this关键字:

一:指代当前类的实例;以下是微软给出的示例

class Employee
{
	private string name;
	private string alias;
	private decimal salary = 3000.00m;

	// Constructor:
	public Employee(string name, string alias)
	{
		// Use this to qualify the fields, name and alias:
		this.name = name;
		this.alias = alias;
	}

	// Printing method:
	public void printEmployee()
	{
		Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
		// Passing the object to the CalcTax method by using this:
		Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
	}

	public decimal Salary
	{
		get { return salary; }
	}
}

class Tax
{
	public static decimal CalcTax(Employee E)
	{
		return 0.08m * E.Salary;
	}
}

class MainClass
{
	static void Main()
	{
		// Create objects:
		Employee E1 = new Employee("Mingda Pan", "mpan");

		// Display results:
		E1.printEmployee();
	}
}
/*
Output:
	Name: Mingda Pan
	Alias: mpan
	Taxes: $240.00
 */

二:用作扩展方法第一个参数的修饰符

三:在索引器中的使用
当我们通过属性访问字段时,通常只能访问单一字段,但是,如果想同时访问多个数据成员时,就需要用到索引器;下面给出示例

	class Program
	{
		static void Main(string[] args)
		{
			Car car = new Car();
			car[1] = "商用车";
			car[2] = "南风";
			car[3] = "华中设备科技有限公司";
			car.Order();
			Console.ReadKey();
		}
	}
	class Car
	{
		private string name;
		private string madeDateTime;
		private string supplier;
		public string this[int index]
		{
			get
			{
				switch (index)
				{
					case 1:
						return name;
					case 2:
						return madeDateTime;
					case 3:
						return supplier;
					default:
						throw new ArgumentOutOfRangeException("index");
				}
			}
			set
			{
				switch (index)
				{
					case 1:
						name =value;
						break;
					case 2:
						madeDateTime = value;
						break;
					case 3:
						supplier = value;
						break;
					default:
						throw new ArgumentOutOfRangeException("index");
				}
			}
		}
		public void Order()
		{
			Console.WriteLine("汽车名字是: "+this[1]+
			", 汽车的生产时间是: "+this[2]+", 汽车的供应商是:"+this[3]);
		}
	}

注意:索引器与数组不同,数组第一个元素是从0开始,索引器第一个元素是从1开始;

Microsoft文档链接如下
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/this

posted @ 2022-03-31 21:20  yangbe1  阅读(167)  评论(0编辑  收藏  举报