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:

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. 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:

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.

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()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top