【问题标题】:Is there a way to make extension-method with List<T>, method(T) as parameters?有没有办法以 List<T>, method(T) 作为参数来制作扩展方法?
【发布时间】:2019-06-07 19:23:00
【问题描述】:

我需要创建一个扩展方法,它将任何类型的List&lt;&gt;List&lt;T&gt;)作为第一个参数,this(因为它是一个扩展)和一个使用与列表相同类型的参数的方法( Method(T some_parameter)) 作为第二个参数。在此方法中,我需要对List&lt;T&gt; 中的每个项目进行一些操作。

delegateDelegate我不是很懂,就是搞不懂。我尝试使用delegatesDelegates、Lambda 表达式,但什么都没有……

  static void Main(string[] args)
  {
       List<item> lisd = new List<item>();
       list.CallForEach((List <item> _list) => EXTENDER.Method(_list));
  }

  public static class EXTENDER
  {

       public static void Method<T>(List<T> list)
       {
            //some code 
       }

       public static void CallForEach<T>(this List<T> list, Action<T> action)
       {
            foreach(var item in list)
            {
                 action(item);
            }
       }
  } 

我需要完全使用“动作”吗? 如果有人知道类似方法的信息,请给我发送参考资料...

【问题讨论】:

  • 阅读Linq有很多类似界面的东西
  • 你这样做的方式很好;这就是 Action&lt;T&gt; 被发明的原因。
  • 如果你想对列表中的每个元素都做一些事情,不要传递对List&lt;item&gt;进行操作的函数,而是传递对item进行操作的函数。
  • 如果你想对每个T而不是源List&lt;T&gt;进行操作,那么List&lt;T&gt;已经有ForEach方法可以做到这一点。
  • lisd.CallForEach(oneItem =&gt; Console.WriteLine(oneItem.SomePropertyOfItem));。正如 Lee 所指出的,List&lt;T&gt; 中已经有一个方法,但是编写自己的方法是一个很好的练习。

标签: c# generics methods system.reactive generic-list


【解决方案1】:

学术目的

给定

public static class Extension
{
   public static void MethodEx<T>(this T item)
   {
      Console.WriteLine(item);
   }

   public static void CallForEach<T>(this List<T> list, Action<T> action)
   {
      foreach (var item in list)
         action(item);
   }
}

用法

public static void Method<T>(T item)
{
   Console.WriteLine(item);
}

static void Main(string[] args)
{
   var list = new List<int>()
                 {
                    1,
                    2,
                    3,
                    4,
                    5,
                    6
                 };

   list.CallForEach(x => x.MethodEx());

   // or you could use a method group
   list.CallForEach(Extension.MethodEx);

   //or if its not in your extension class
   list.CallForEach(Method);


   // ForEach is already part of the List class
   list.ForEach(x => x.MethodEx());
   list.ForEach(Extension.MethodEx);
   list.ForEach(Method);

}

输出所有示例

1
2
3
4
5
6

【讨论】:

  • 注意:您也可以拨打list.CallForEach(Extension.MethodEx)
  • list.CallForEach(x =&gt; x.MethodEx()) x. 只有 6 个默认 int 方法并且看不到任何一个:MethodEx&lt;T&gt;(T item)MethodEx&lt;int&gt;(int item)MethodEx&lt;T&gt;(this T item)MethodEx&lt;T&gt;(this List&lt;T&gt; item)。我能做错什么?还有我对ForEach 的任何尝试都被粉碎了......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
相关资源
最近更新 更多