c#创建静态类,在其中定义一个泛型方法,实现查找数组元素的功能

本文介绍了如何在C#中创建静态类,并定义一个泛型方法来实现查找数组元素的功能。由于泛型不能直接比较,需要使用where T : IComparable约束。同时,由于静态类不能直接返回结果,只能在类内部输出。讨论了比较和排序的概念,以及IComparable和IComparer接口在自定义比较逻辑中的应用,特别是它们的泛型实现IComparable<T>和IComparer<T>。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型中不能直接比较,要用where T :IComparable

而且静态类中不能传递出来结果。。只能在静态类的内部输出结果。

1:比较和排序的概念

    比较:两个实体类之间按>,=,<进行比较。

    排序:在集合类中,对集合类中的实体进行排序。排序基于的算法基于实体类提供的比较函数。

    基本型别都提供了默认的比较算法,如string提供了按字母进行比较,int提供了按整数大小进行比较。

2:IComparable和IComparer

    当我们创建了自己的实体类,如Student,默认想要对其按照年龄进行排序,则需要为实体类实现IComparable接口。

   可使用IComparer来实现一个自定义的比较器。

3:IComparable和IComparer的泛型实现IComparable<T>和IComparer<T>

具体见:http://www.cnblogs.com/luminji/archive/2010/09/30/1839038.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    static class index
    {
        public static void A<T>(T b,T[] a) where T : IComparable  //要加static
        {
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i].Equals(b))
                    Console.Write("{0} ",i+1);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("元素所在位置是:");
            int[] a = {1,2,3,4,5,2};
            index.A<int>(2,a);
            Console.ReadKey();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值