2013-10-16 53 views
0

在我的課程中,我有一個屬性ImageNames,我想要獲取和設置。我試過添加set,但它不起作用。我該如何設置這個屬性?使用get和set來實現屬性?

public string[] ImageNames 
{ 
      get 
      { 
       return new string[] { }; 
      } 

      //set; doesn't work 
} 
+0

您可能是指屬性而不是屬性。 「'不起作用'是什麼意思? – haim770

+0

我沒有在這裏看到任何'屬性... ...看起來像你在談論財產 - 請編輯您的文章使用C#條款。 –

+0

對不起,剛剛編輯。仍然不太熟悉C#的細微差別:) –

回答

8

您通常會希望支持字段:

private string[] imageNames = new string[] {}; 
public string[] ImageNames 
{ 
     get 
     { 
      return imageNames; 
     } 

     set 
     { 
      imageNames = value; 
     } 
} 

或者使用自動屬性:

public string[] ImageNames { get; set; } 

話雖這麼說,你可能希望只露出一個集合,它允許人名稱,不能替換整個名稱列表,即:

private List<string> imageNames = new List<string>(); 
public IList<string> ImageNames { get { return imageNames; } } 

這將允許您添加名稱並將其刪除,但不會更改集合本身。

2

閱讀自動財產

public string[] ImageNames { get; set;} 

你需要一個變量來設置,如果你想設置什麼你的String []。

像這樣:

private string[] m_imageNames; 

    public string[] ImageNames 
    { 
     get { 
      if (m_imageNames == null) { 
       m_imageNames = new string[] { }; 
      } 
      return m_imageNames; 
     } 
     set { 
      m_imageNames = value; 
     } 
    } 

而且,這些被稱爲屬性,而不是屬性。一個屬性是你可以在方法或類或屬性上設置的東西,它將以某種方式進行轉換。例如:

[DataMember]  // uses DataMemberAttribute 
public virtual int SomeVariable { get; set; }