【问题标题】:How to create a method similar to ForEach如何创建类似于 ForEach 的方法
【发布时间】:2021-03-01 09:35:27
【问题描述】:

这纯粹是学术性的,但我如何创建像 ForEach 这样的方法?

如果我想做类似以下的事情,请说:

 SomeTenumerable.MyOwnFunction(x =>
         {
            x.Id = 0;
            x.Order_Id = 0;
         });

注意:我刚刚熟悉func<T,TResult>,所以我不确定它是否是同一件事。

如果你能告诉我我想要达到的目标的正确名称/标签,我猜它是某种代表?

【问题讨论】:

标签: c#


【解决方案1】:

在这里演示 - https://dotnetfiddle.net/v7JKoo

.我经常使用的每个扩展 - 取自 http://extensionmethod.net/csharp/ienumerable-t/each-t

public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
    if (items == null) return;

     foreach (var item in items)
        action(item);
}

例子:

var items = new List<Item>();
// populate items
items.Each(item => item.DoSomething());

是的,您正在传递一个委托(这里是一个动作)来对每个项目执行

PS 如果您要退货,请查看 linqs .Where 或 .Select

【讨论】:

  • items 怎么可能是null?我猜扩展方法也可以静态调用?
  • @PaulBellora:扩展方法总是被静态调用。它们是静态方法。是的,作为this 传递的引用可以是null
  • @PeterDuniho 不错!深夜编码失败 - 现在放下键盘
【解决方案2】:

我认为你想要做的是创建一个扩展方法 (MSDN)

ForEach 是 List 类中的一个方法(可以看代码here)。由于您无法向类添加方法,因此您可以创建一个扩展方法,该方法存在于您的项目中,但可以作为原始 List 类的一部分使用。

假设您的项目使用此接口

public interface IYourInterface
{
    int Id;
    int Order_Id;
}

在静态类中创建静态方法:

static class HelperMethods
{
    public static void ResetAll(this List<IYourInterface> collection)
    {
        collection.ForEach(x =>
        {
            x.Id = 0;
            x.Order_Id = 0;
        });
    }
}

然后在任何 List 实例上使用该方法。

var collection = new List<IYourInterface>();
collection.ResetAll();

var otherStuff = new List<string>();
// This won't work because because List<string> cannot
// be converted to List<IYourInterface>
// otherStuff.ResetAll();    

【讨论】:

    【解决方案3】:

    添加属性类

    Public MyClass
    {
      public static int Id {get;set;}
      public static int Order_Id{get;set;} 
    }
    

    你可以这样设置

    IEnumerable<MyClass> myclass = new IEnumerable<MyClass>(
    {
        Id = 0;
        Order_Id = 0;
    });
    

    你可以通过查询,serach throw等。

    看到这个问题,Here 这个问题本身不是答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2013-07-05
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多