列表的扩展方法(Extension Method for a List)

[db:摘要]

列表的扩展方法(Extension Method for a List)

我有一个实现IComparable类的Order类的列表,并覆盖了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"); } }

现在我添加了一个扩展方法Show to List,它按照我的预期工作

扩展类

public static class ListExtension { public static void Show(this List<Order> list) { foreach (var item in list) { Console.WriteLine(item.ToString()); } } }

现在我想打开我的方法Show Generic:

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

但我无法调用通用扩展方法。 你可以帮我吗 。

I have a List of a class Order which implements IComparable and override the Tostring method

Order class:

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"); } }

Now i added an extension Method Show to List and it is working as i expected

Extension Class

public static class ListExtension { public static void Show(this List<Order> list) { foreach (var item in list) { Console.WriteLine(item.ToString()); } } }

Now i would like to turn my method Show Generic :

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

But i can not call the generic extension method. Can you help me .

最满意答案

您错过了函数名称后的<T>以使其具有通用性:

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

You missed the <T> after the name of the function to make it generic:

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

发布者:admin,转转请注明出处:http://www.yc00.com/web/1689539548a264472.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信