規則一:使用屬性而不是方法

原因:

1. 所有的bind方法綁定屬性。

data bind的機制是使用反射的方法,通過屬性名稱調用相應的方法。

2.使用屬性讓程序更有彈性。 

  如戶要求名字不能爲空,只要如下修改程序即可

  public class Customer{

    private string _name;

public string Name

{

get { return _value;}

set 

{

//判定是否爲空,如果是空拋出錯誤

if (string.IsNullorEmpty(value))

throw new ArgumentException("名字不能不填寫",“name");

name = value;

}

}

  }


3. 可以很容易的增加多線程支持

  public class Customer{

private object syncHandle = new object()

private string _name;

public string Name

{

get 

lock(syncHandle ){return _value;}

}

set 

{

//判定是否爲空,如果是空拋出錯誤

if (string.IsNullorEmpty(value))

throw new ArgumentException("名字不能不填寫",“name");

lock(syncHandle ){name = value;}


}

}

  }


4. 屬性可以使用虛函數

 public class Customer{

    public virtual strring Name

   {

       set;

       get;

   }

}


屬性定義也可以採用以上的簡略方式。編譯器會自動加上私有的局部變量及屬性的方法體定義。


5.屬性可以在接口中進行定義

public interface INameValuePaire<T>

{

    string Name

    {

         get; 

    }

  T value

  {

      get;

      set;

  }

}


所有在普通方法上適應的結構,在屬性中都適應。比如你可以把get方法的訪問範圍定義爲public,把set方法的訪問範圍定義爲protected.

 public class Customer{

    public virtual strring Name

   {

       protected set;

       get;

   }

}


6.屬性也可以定義成數組,進行訪問

  • 一維數組的屬性定義

public int this[int index]

{

    get {return  theValues[index];}

    set{ theValues[index] = value;}

}


//屬性的使用

int val = someObject[index]


  • directionary或map數據類型的屬性定義
public Address this[string name]
{
     get {return  addressValues[name] ;}
     set { addressValues[name] = value;}
}

  • 多維數組的定義方法與一維數組類似。如:
public int this[int x, int y]
{
    get { return ComputeValue(x, y); }
}


public int this[int x, string Name]
{
    get { return ComputeValue(x, Name); }
}

注意:所有的數組屬性只能以this,進行定義,所以不允許有相同的參數列表。索引屬性也稱爲索引器,通過它,可以像數組一樣引用類的實例。但是索引屬性不能使用static.

如:

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}













        




發佈了41 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章