In 1 of my classes, I have an property ImageNames
that I want to get and set. I tried adding set
but it doesn't work. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.