看了篇文章,上面说set和get方法其实就是属性,为了使代码更安全而用的,其属性就是只读,只写和可读可写这3种属性
但具体的使用方法和例子有点看不懂,请各位高手们帮忙详细解释下,谢谢

解决方案 »

  1.   

    private int test1 = 0;
    public int Test1
    {
        get
        {
            return test1;
        }
    }这就是只读
    在外面只能获取Test1,而不能对Test1进行写操作
      

  2.   

    还可以通过属性控制写入的值  
      private int num;
        //只读属性
        public int Num
        {
            get { return this.num; }
        }    private string str;
        //只写属性
        public string Str
        {
            set { this.str = value; }
        }    private double doub;
        //读写属性
        public double Doub
        {
            get { return this.doub; }
            set
            {
                //有条件的写,如果大于0,返回value,否则返回0
                if (value >= 0)
                {
                    this.doub = value;
                }
                else
                {
                    this.doub = 0;
                }
            }    }
      

  3.   


    public class A
    {
        public A()
    {}int id;
    public int ID
    {
    get {return id;}
    }
    }
    public class B
    {
    int n;
    public B()
    {
    A a=new A();
    n=a.ID;//正确,因为a.ID有get,可以获取。
    a.ID=2;//错误,因为a.ID没有set,不能写入。
    }
    }
    所以,属性主要是对于外部而言(当然类内部也能使用),没有get的就不能获取,所以就是只写;没有set的就不能写入,所以就是只读,有get有set,就是可写可读了。
      

  4.   

    class A
    {
      int i=0;
      public int I
      { 
       get
       {
        return i;
       }
       set
        {
         i=value;
        }
       }
    }class test
    {
      A a=new A();
      a.I=5;
      Console.Write(a.I);
    }
      

  5.   

    誰說的set和get方法其實就是屬性?
      

  6.   


    private string property;
    public string Property
    {
       get{return property;}
       set {property=value}
    }get和set就是兩個方法,編譯後會分別成為get_Property和set_Property。
    property是private限定,所以無法在外部訪問
    而Property這個屬性,是根據get和set的設置來調用get_Property或set_Property進行讀取或賦值。
    如果沒有定義set,就無從賦值,所以起到了衹讀的效果。