天天看点

C# This用法 get,set属性value用法

C#中,this关键字代表当前实例,我们可以用this.来调用当前实例的成员方法,变量,属性,字段等;

也可以用this来做为参数状当前实例做为参数传入方法.

还可以通过this[]来声明索引器

public class DictionaryClass
    {
       
      private List<string> PRISTR = new List<string>();//私用
        public string this[string str]//想将PRISTR值给尾部用,但通过属性来控制
        {
            set
            {
                if (!this.PRISTR.Contains(str))
                {
                    str = value;//外部传入的值
                    this.PRISTR.Add(str);
                }
            }
            get
            {
                return "kong";
            }

        }
    }
  class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            DictionaryClass dd = new DictionaryClass();
            string str="wy love";
            //string ret = dd[str];//get 方法 只能读
            dd[str] = "dd";//set 方法 只能写

        }
    }
           

执行dd[str]="dd"时,进入set属性,将"dd"赋值给Value,list.add("dd");

PRISTR为私用,不想被随意使用更改,通过属性来控制修改赋值