簡體   English   中英

C# 將值附加到空數組 int[] 不起作用

[英]C# appending values to empty array int[] doesn't work

我正在做一個 windows 表單應用程序,我需要為某些列表框操作聲明空數組。 但我無法為數組增加價值。 當我在添加一個值后嘗試打印數組的長度時,我一直讀取值 0。

public partial class Form1 : Form
    {
        public static int[] arrayOfNumbers = new int[] { };
        public Form1()
        {
            InitializeComponent();
        }
        
        public void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(textBox1.Text);
           
            arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text));
            Console.WriteLine(arrayOfNumbers.Length);
            
        }

Enumerable.Append將一個項目附加到一個序列並返回它,因此您需要使用它來為該字段重新分配一個新數組。 但它不返回數組而是IEnumerable<T> ,因此您必須附加ToArray

arrayOfNumbers = arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text)).ToArray();

數組是一個固定大小的集合,無論如何都無法修改。

除了Tim Schmelter 的回答絕對正確之外,OP 最明顯想要做的是使用List<int>及其Add方法而不是數組1

Append是所謂的 LINQ 方法,它將返回附加了該值的數組的“副本” 2 ,而不是修改您調用它的實例,這不是預期發生的情況。

public partial class Form1 : Form
{
    public static List<int> arrayOfNumbers = new(); // use a List<int>

    public Form1()
    {
        InitializeComponent();
    }
    
    public void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add(textBox1.Text);
        
        arrayOfNumbers.Add(Convert.ToInt32(textBox1.Text)); // extend instance with Add
        Console.WriteLine(arrayOfNumbers.Count); // use List's Count property
    }

1我想 OP 有一個 Python 背景,因為 Python “列表”由於方括號看起來像 C# arrays ,並且沒有固定的大小。 與 Python 列表對應的 C# 是List實例,但是方法名稱略有不同,例如Add而不是Append

2由於LINQ是惰性求值的,因此該語句非常簡單,它只返回一個枚舉器,該枚舉器在迭代后具有您希望它具有的效果,從不修改您調用它的實例或自行創建新實例。

public void Submit_Click(object sender, RoutedEventArgs e)
    {
        ListUser[] Acts = {};     //Empty string array
        int length = Acts.Length; //get array length to int
        int ActInt = length;      //assign to separate int var


                                  //--if--//
                                  //Check if array is 0 length and append
                                  //values from two textboxes to the Acts 
                                  //array.
                                  //Get new length of Acts array and assign 
                                  //to int length and int ActInt.
                                  //Then create an array to hold a copy of 
                                  // the values using correct length
                                  //Bind Acts array to ListView DataSource
                                  //--else--//
                                  //If Acts array is not empty "0" write 
                                  //vals to console. AKA Append again.
         if (ActInt==0)
           {
               Acts = Acts.Append(new ListUser(NameEntry.Text, TimeEntry.Text)).ToArray();
               length = Acts.Length;
               ActInt = length;                   
               ListUser[] ActsOld = new ListUser[ActInt];
               System.Array.Copy(Acts, ActsOld, ActInt);
               ActsList.ItemsSource=Acts;
           }
        else if (Acts!=0)
           {
               /*Append to array here and remove foreach*/
               //--|--//
               //--V--//
               foreach (var i in Acts)
               {
                   Console.WriteLine(i);
               }
           }
    }

其中 ListUser[] 是第二個 Class 文件,用於定義數組的屬性

public class ListUser
    {
        public string lName { get; set; }
        public string lTime { get; set; }

        public ListUser(string lname, string ltime)
        {
            lName = lname;
            lTime = ltime;
        }

    }

感謝您的幫助Tim使用您的答案

arr = arr.Append(element(params)).ToArray();

工作完美。

如果有人可以建議一種快速而骯臟的方法來單擊並拖動以重新排序 ListView / GridView 中的條目,任何幫助都會很棒!!

<ListView x:Name="ActsList">
                <ListView.View>
                    <GridView x:Name="ActsListGrid">
                        <GridView.Columns>
                            <GridViewColumn Width="300"
                                            Header="Name"
                                            DisplayMemberBinding="{Binding lName}" />
                            <GridViewColumn Width="80"
                                            Header="time"
                                            DisplayMemberBinding="{Binding lTime}" />

                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM