使用 get 和 set 实现属性

本文关键字:实现 属性 set get 使用 | 更新日期: 2023-09-27 18:35:42

在我的一个类中,我有一个想要获取和设置的属性ImageNames。我尝试添加set但它不起作用。如何使此属性可设置?

public string[] ImageNames
{
            get
            {
                return new string[] { };
            }
            //set; doesn't work
}

使用 get 和 set 实现属性

您通常需要一个支持字段:

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; } }

这将允许您添加和删除名称,但不能更改集合本身。

如果你想

为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; }

只需使用自动属性

public string[] ImageNames { get; set;}

在这里阅读

http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx