lwj_C#_泛型使用

来源:互联网 发布:聊骚软件靠谱吗 编辑:程序博客网 时间:2024/04/30 19:33
    public static class Test2
    {
        //数组 转成(拼接)  字符串;
        public static string CompoundString<T>(T[] arr)
        {
            string str = "";//null;
            foreach (T t in arr)
            {
                str += (t.ToString() + " ");
            }
            return str;
        }

       
    }

    public class Test {
         //冒泡排序                                               //实现接口
        public static void Sort <T> (T[] arraywhere T : IComparable{
            for (int i = 0i < array.Length-1i++)
            {
                for (int j = 0j < array.Length - i - 1j++)
                {
                    if (array[j].CompareTo(array[j+1]) == 1)
                    {
                        T temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                    }
                }

            }
            //foreach (T i in array)
            //{
            //    Console.WriteLine(i);
            //}
        }
    }

    //结构体
    public struct STest : IComparable
    {
        public float s;

        public int CompareTo(object obj)
        {
            STest st = (STest)obj;
            //自己写的比较
            if (this.s > st.s)
            {
                return 1;
            }
            else if (this.s < st.s)
            {
                return -1;
            }
            else
            {
                return 0;
            }

        }
    }
    class MainClass
    {
        public static void Main(string[] args)
        {
           string str = Test2.CompoundString<string>(new[] { "jiangkai""shi""sb" });
            Console.WriteLine(str);

            Test.Sort<string>(new[]{"dfsd","jkm","Dhf","erter"});
            Test.Sort<int>(new[]{767,342,3,12,4545,1});

            STest st_1 = new STest();
            st_1.s = 12f;
            STest st_2 = new STest();
            st_2.s = 24f;
            STest st_3 = new STest();
            st_3.s = 65f;

            int a = st_1.CompareTo(st_2);
            Console.WriteLine(a);
            //结构体数组
            STest [] st = { st_1st_2st_3 };
             
            Test.Sort<STest>(st);
            foreach (STest i in st)
            {
                Console.WriteLine(i.s);
            }


        }
    }