程序员开发实例大全宝库

网站首页 > 编程文章 正文

C#编程源代码:在数组中插入新元素

zazugpt 2024-09-07 01:51:22 编程文章 19 ℃ 0 评论

C#编程,在数组中插入新元素

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    
    public partial class Form1 : Form
    {
        private int[] array1;
        public Form1()
        {
            InitializeComponent();
        }
        static int[] AddArray(int[] Array3, int Index, int Value)
        {
            if (Index > (Array3.Length))
                Index = Array3.Length+1;
            int[] TemArray = new int[Array3.Length + 1];
            for (int i = 0; i < TemArray.Length; i++)
            {
                if (Index > 0)
                {
                    if (i < (Index - 1))
                        TemArray[i] = Array3[i];
                    else if (i == (Index -1))
                        TemArray[i] = Value;
                    else
                        TemArray[i] = Array3[i-1];
                }
                else
                {                    
                    TemArray[0] = Value;                    
                }
            }
            return TemArray;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox3.Clear();
            int[] array2=new int[array1.GetUpperBound(0) + 1];
            int index;
            int value;
            if(int.TryParse(tex_wz.Text,out index) && int.TryParse(tex_value.Text, out value))
            {
                array2=AddArray(array1, index, value);
            }
            else
            {
                MessageBox.Show("请重新输入数据","information");
            }
            for (int i = 0; i < array2.GetUpperBound(0) + 1; i++)
            {                
                textBox3.Text = textBox3.Text+array2[i].ToString() + " ";
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {            
            textBox1.Clear();
            Random r = new Random();
            array1 = new int[r.Next(4, 10)];
            displayArray();
        }
        private void displayArray()
        {
            Random r = new Random();
            for (int i = 0; i < array1.GetUpperBound(0) + 1; i++)
            {
                array1[i] = r.Next(1, 10);
                textBox1.Text = textBox1.Text + array1[i] + " ";
            }
        }
    }
}

结语:

会使用随机对象Random的Next()方法随机生成数据,掌握获得数组索引方法GetUpperBound,掌握TryParse方法进行参数传递。

喜欢的请关注和收藏!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表