[英]getters setters array
Probably a really simple problem i can't fix - I'm starting out with C# and need to add values to an array with a getter/setter method for example: 可能是一个无法解决的非常简单的问题-我从C#开始,需要使用getter / setter方法将值添加到数组中,例如:
public partial class Form1 : Form
{
string[] array = new string[] { "just","putting","something","inside","the","array"};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Array = "gdgd";
}
public string[] Array
{
get { return array; }
set { array = value; }
}
}
} }
This is never going to work: 这永远行不通:
Array = "gdgd";
That's trying to assign a string
value to a string[]
property. 试图将
string
值分配给string[]
属性。 Note that you can't add or remove elements in an array anyway, as once they've been created the size is fixed. 请注意,无论如何您都无法添加或删除数组中的元素,因为一旦创建元素,其大小便是固定的。 Perhaps you should use a
List<string>
instead: 也许您应该使用
List<string>
代替:
public partial class Form1 : Form
{
List<string> list = new List<string> {
"just", "putting", "something", "inside", "the", "list"
};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List.Add("gdgd");
}
public List<string> List
{
get { return list; }
set { list = value; }
}
}
Note that having the public property is irrelevant here anyway, as you're accessing it from within the same class - you can just use the field: 请注意,无论如何,这里都没有公共属性,因为您是从同一类中访问它的-您可以使用以下字段:
private void button1_Click(object sender, EventArgs e)
{
list.Add("gdgd");
}
Also note that for "trivial" properties like this you can use an automatically implemented property: 还要注意,对于像这样的“琐碎”属性,可以使用自动实现的属性:
public partial class Form1 : Form
{
public List<string> List { get; set; }
public Form1()
{
InitializeComponent();
List = new List<string> {
"just", "putting", "something", "inside", "the", "list"
};
}
private void button1_Click(object sender, EventArgs e)
{
List.Add("gdgd");
}
}
inside your set method you need to add code so that it can add to a specific array location, unless you are sending it an array, if that is the case then what you have should work. 在set方法中,您需要添加代码,以便可以将其添加到特定的数组位置,除非您要向其发送数组,如果是这种情况,那么您应该拥有的内容就会起作用。
if you send it a string, like you are you need to specify the array location. 如果您将其发送为字符串,则需要指定数组位置。
Array[index] = "gdgd"
otherwise it looks like you are assigning to a string variable and not an Array 否则,看起来您正在分配给字符串变量而不是数组
Use a List to hold the values. 使用列表保存值。 When you need to return the array, use List.ToArray()
当您需要返回数组时,请使用List.ToArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.