【问题标题】:How to insert an item into an array at a specific index in c#?如何将项目插入到c#中特定索引处的数组中?
【发布时间】:2020-07-24 23:15:15
【问题描述】:

我有 2 个文本框 (txt1, txt2)、2 个单选按钮 (rb1, rb2)、2 个数字上下框(nud1,nud2)combo box。 我想将上面的数据存储在一个数组中,在命名的地方。数组名称是 mycode。 例子: rb1 = mycode[3], combobox=mycode[0], txt1=mycode[6]....等 最终我想在我的数组中连接一些命名的 idex。并在消息框中显示 例子: 我的代码是mycode[3] + mycode[7] 怎么做? 但我不知道最好的选择是做这个数组、列表还是其他?

【问题讨论】:

  • 如果你不想让一个类保存 ytour 值,Dictionary 可能是一个选项
  • @timur 我不知道如何使用字典来完成这项工作。我会尝试谷歌并学习。
  • 我喜欢的文档页面有一个例子。它比您需要的要长一点,但它证明了这一点。也许看看它,看看它是否适合您的用例?

标签: c# list arraylist indexing


【解决方案1】:

这就是你要找的吗??

myCode[0] = myValue

【讨论】:

    【解决方案2】:

    要使用数组,可以像这样创建一个空数组;

    var arr = Object[7] //This allows you to add different data types, and 7 sets the array length to hold 7 items
    arr[0] = txt1.text;
    arr[1] = txt2.text;
    

    你可以这样连接:

    Console.Write($" my code is {arr[1]} + {arr[2]}")
    

    【讨论】:

    • 如何将字符串值和int十进制值(numericupdownbox)添加到单个数组中?
    • 我已更新答案以使用对象数组。请注意,如果没有显式转换,您无法将字符串和小数相加
    【解决方案3】:

    数组对于您的需求来说太原始​​了。正如@timur 建议的那样,您可以创建一个Dictionary<TKey,TValue>,其中您的“TKey”为string,您的“TValue”为object。你可以这样使用它:

    // Create a new dictionary of objects, with string keys.
    //
    Dictionary<string, object> mycode= 
        new Dictionary<string, object>();
    
    // Add some elements to the dictionary. There are no 
    // duplicate keys, but some of the values are duplicates.
    mycode.Add("txt1", "Hello");
    mycode.Add("rb1", 2);
    

    您可以使用实际的控件引用而不是它们的名称作为字符串。所有控件都继承自Control 类。所以你可以使用Dictionary&lt;Control, object&gt;

    在这里,我为您提供一个简单的示例,其中包含一个具有 TextBox (textBox1)、一个 NumericUpDown (numericUpDown1) 和一个按钮 (button1) 的表单。

            Dictionary<Control, object> myDictionary = new Dictionary<Control, object>();
    
            private void numericUpDown1_ValueChanged(object sender, EventArgs e)
            {
                if (myDictionary.ContainsKey((Control)sender))
                    myDictionary[(Control)sender] = ((NumericUpDown)sender).Value;
                else
                    myDictionary.Add((Control)sender, ((NumericUpDown)sender).Value);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                if (myDictionary.ContainsKey(numericUpDown1))
                    textBox1.Text = ((decimal)myDictionary[numericUpDown1]).ToString();
            }
    

    用这种方法你必须做很多演员,你必须小心。

    【讨论】:

    • 你是什么意思“openWith”?以及如何连接 Dictionary 对象?
    • "openWith" 是错字。字典是键值对的集合。它不是单个 KeyValuePair,因此您可以添加任意数量的键值对。
    猜你喜欢
    • 2010-10-09
    • 2021-07-08
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多