Ced*_*lle 1 c# arrays getter setter element
可能是一个我无法解决的非常简单的问题 - 我开始使用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; }
}
}
Run Code Online (Sandbox Code Playgroud)
}
Jon*_*eet 10
这永远不会起作用:
Array = "gdgd";
Run Code Online (Sandbox Code Playgroud)
那是试图string为一个string[]属性赋值.请注意,无论如何都无法在数组中添加或删除元素,因为一旦创建它们,大小就会被修复.也许你应该用一个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; }
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,无论如何都要使公共属性无关紧要,因为您正在同一个类中访问它 - 您可以使用以下字段:
private void button1_Click(object sender, EventArgs e)
{
list.Add("gdgd");
}
Run Code Online (Sandbox Code Playgroud)
另请注意,对于像这样的"普通"属性,您可以使用自动实现的属性:
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");
}
}
Run Code Online (Sandbox Code Playgroud)