gpt4 book ai didi

c# - setter/getter setter 数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:54 25 4
gpt4 key购买 nike

可能是一个我无法解决的非常简单的问题 - 我从 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; }
}
}

}

最佳答案

这永远不会起作用:

Array = "gdgd";

那是试图分配 string值为 string[]属性(property)。请注意,无论如何您都不能在数组中添加或删除元素,因为一旦创建了它们,其大小就是固定的。也许你应该使用 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; }
}
}

请注意,无论如何,拥有 public 属性在这里是无关紧要的,因为您是从同一个类中访问它 - 您可以只使用该字段:
private void button1_Click(object sender, EventArgs e)
{
list.Add("gdgd");
}

另请注意,对于像这样的“琐碎”属性,您可以使用自动实现的属性:
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");
}
}

关于c# - setter/getter setter 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18190036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com