1.7C#语言基础-泛型

泛型编程

  • 一种编程范式
  • 数据抽象化
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 ExtensiveList
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        class Types<T>
        {
            public T Num;
            public T Name;
            public T Sex;
            public T Age;
            public T Salary;
            public T Birth;
        }
       

        private void button1_Click(object sender, EventArgs e)
        {

            Types<object> Exte = new Types<object>();//创建泛型对象
            Exte.Age = 18;
            Exte.Num = 1001;
            Exte.Name = "小明";
            Exte.Birth = Convert.ToDateTime("1994-05-01");
            Exte.Salary = 1500.45F;
            Exte.Sex = "男";

            textBoxAge.Text = Exte.Age.ToString();
            textBoxName.Text = Exte.Name.ToString();
            textBoxSalary.Text = Exte.Salary.ToString();
            textBoxNo.Text = Exte.Num.ToString();
            textBoxSex.Text = Exte.Sex.ToString();
            dateTimePickerBirth.Text = Exte.Birth.ToString();
            
        }
    }
}

数组去重

  • 先排序
  • 判断相邻是否相等
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 RemoveSameNum
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        static int[] RemoveNum(int[] arr)//arr已经排序了,去重,就是判断响铃的是否相同即可
        {
            List<int> arr2 = new List<int>();
            for(int i=0; i<arr.Length-1; i++)
            {
                if(arr[i]!=arr[i+1])
                {
                    arr2.Add(arr[i]);
                }
            }
            arr2.Add(arr[arr.Length - 1]);//最后一个添加进去
            return arr2.ToArray();//将泛型转成数组
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            int[] arr = new int[] { 1, 5, 7, 2, 2, 4, 9, 4, 7, 23, 21 };
            label1.Text += string.Join(",",arr);
            //排序
            Array.Sort(arr);
            int[] newArr = RemoveNum(arr);
            label2.Text += string.Join(",", newArr);


        }
    }
}
posted @ 2018-12-17 10:04  随时静听  阅读(118)  评论(0编辑  收藏  举报