C#——this关键字(2,3)(含求助贴)

这次来看一看this关键字的第二个用法:将对象作为参数传递到其他方法

----------------------------------------------------------------------------------

2016-12-17 21:00:06

顺便把第三种用法也说了吧:声明索引器

----------------------------------------------------------------------------------

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 //我们假设要把一个学生的成绩按70%折算
 8 
 9 namespace @this
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Student student = new Student();
16             student.GetMessage("Mark");
17             student.PrintScore ();
18         }
19     }
20 
21     class Student
22     {
23         public string Name { get; set; }
24         private int  Score = 100;
25 
26         public void GetMessage(string Name)
27         {
28             //这个this用法属于第一种:限定被相似的名称隐藏的成员
29                   this.Name = Name;
30         }
31 
32         public int score
33         {
34             get { return Score; }
35         }
36 
37         public void PrintScore()
38         {
39             Console.WriteLine("My Name Is {0}, My Score Is {1}",Name,score );
40             Console.WriteLine("How many points after converting? ");
41             Console.WriteLine("The Converted Score Is {0}",Convert .ConvertedScore(this));//注意:这里要用this传参数了
42         }
43     }
44 
45     class Convert
46     {
47         public static int  ConvertedScore(Student stu)//折算分数
48         {
49             return (int)(0.7 * stu.score);//强制类型转换一下
50         }
51     }
52     
53 }

 41行代码 Convert .ConvertedScore(this) 里面的this也便就是“折算后的分数”

2016-12-17 20:41:04编辑

有网友回复解答到 这里的this就代表当前引用的实例。

把谁传进来的,这个“this”就代表它 这里是指“100”这个值

-------------------------------------------------------------------

-------------------------------------------------------------------

声明索引器

算是一个固定语法吧:

例如:

 public object this[int index]
        {
            get { /* return the specified index here */ }
            set { /* set the specified index to value here */ }
        }

-------------------------------------------------------------------

说实话,我对this关键字的这个用法理解的并不是太透彻,用的时候也是云里雾里的,所以希望网友们能够积极的给我评论,给予我一些帮助,给我讲解一下这个地方,在下感激不尽

;)----------To be continued!

原文地址:https://www.cnblogs.com/GeekDragon/p/6081117.html