列表的扩展方法

Gha*_*sen 4 c#

我有一个类的List列表,它实现了IComparable并覆盖了Tostring方法

订单类:

public class Order : IComparable
    {
        public int id { get; set; }
        public DateTime date { get; set; }
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return 1;
            }
            else
            {
                Order order = obj as Order;
                if (order == null)
                {
                    throw new ArgumentException("object is not an order");
                }
                return this.date.CompareTo(order.date);
            }
        }
        public override string ToString()
        {
            return this.id+"--"+this.date.ToString("dd/MM/yyyy");
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我添加了一个扩展方法Show to List,它正如我预期的那样工作

扩展类

public static class ListExtension

    {
        public static void Show(this List<Order> list)
        {

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我想转向我的方法Show Generic:

 public static class ListExtension<T>
   {
        public static void Show(this List<T> list)
        {

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我无法调用泛型扩展方法.你能帮助我吗 .

And*_*rew 5

您错过了<T>函数名称之后的通用名称:

public static class ListExtension
{
    public static void Show<T>(this List<T> list)
    {
        foreach (var item in list)
        {
            Console.WriteLine(item.ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)