[英]Implementing property with get and set?
In 1 of my classes, I have an property ImageNames
that I want to get and set. 在我的一门课中,我有一个要获取和设置的
ImageNames
属性。 I tried adding set
but it doesn't work. 我尝试添加
set
但不起作用。 How do I make this property settable? 如何使此属性可设置?
public string[] ImageNames
{
get
{
return new string[] { };
}
//set; doesn't work
}
You typically would want a backing field: 通常,您需要一个后备字段:
private string[] imageNames = new string[] {};
public string[] ImageNames
{
get
{
return imageNames;
}
set
{
imageNames = value;
}
}
Or use an auto-property: 或使用自动属性:
public string[] ImageNames { get; set; }
That being said, you may want to just expose a collection which allows people to add names, not replace the entire list of names, ie: 话虽如此,您可能只想公开一个允许人们添加名称的集合,而不是替换整个名称列表,即:
private List<string> imageNames = new List<string>();
public IList<string> ImageNames { get { return imageNames; } }
This would allow you to add names and remove them, but not change the collection itself. 这将允许您添加名称并删除它们,但不能更改集合本身。
You'll need a variable to set, if you want to set anything to your string[]. 如果要为字符串[]设置任何内容,则需要设置一个变量。
Like this: 像这样:
private string[] m_imageNames;
public string[] ImageNames
{
get {
if (m_imageNames == null) {
m_imageNames = new string[] { };
}
return m_imageNames;
}
set {
m_imageNames = value;
}
}
Also, these are called properties, not attributes. 同样,这些被称为属性,而不是属性。 An attribute is something you can set on a method or class or property that will transform it in some way.
属性是可以在方法,类或属性上设置的属性,可以通过某种方式对其进行转换。 Example:
例:
[DataMember] // uses DataMemberAttribute
public virtual int SomeVariable { get; set; }
Just use an auto property 只需使用自动属性
public string[] ImageNames { get; set;}
Read here 在这里阅读
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx http://msdn.microsoft.com/zh-CN/library/x9fsa0sw.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.