C#——设计一个泛型类,实现任意类型的数据排序

首先设计界面:一个Label标签

编写代码:‘

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

namespace 泛型类
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "";
            Data<int> a = new Data<int> (3, 5, 2, 8, 7, 6 );
            a.sort();
            label1.Text = ""+a.display();
            Data<float> b = new Data<float>(3.5f, 7.5f, 2.1f, 9.9f, 5.4f, 6.8f);
            b.sort();
            label1.Text += "" + b.display();
        }
    }
    //定义泛型类
    class Data<T>
    {
        private T[] datas;
        public Data(params T[] datas)
        {
            this.datas = datas;
        }
        //排序
        public void sort()
        {
            for (int i = 0; i < datas.Length; i++)
            {
                for (int j = i; j < datas.Length; j++)
                { 
                    if(Convert .ToDouble(datas[i])<Convert.ToDouble (datas[j]))
                    {
                        T t = datas[i];
                        datas[i] = datas[j];
                        datas[j] = t;
                    }
                }
            }
        }
        //输出数组元素的方法
        public string display() 
        {
            string info = "\n";
            for (int i = 0; i < datas.Length; i++)
            {
                info += datas[i].ToString() + "    ";
            }
            return info;
        }
    }

}
 

运行结果:

猜你喜欢

转载自blog.csdn.net/lmm0513/article/details/88913106