【问题标题】:What is the c# equivalent of Java 8 java.util.function.Consumer<>?Java 8 java.util.function.Consumer<> 的 c# 等价物是什么?
【发布时间】:2016-07-26 18:00:57
【问题描述】:

C#中是否有与此接口等效的接口?

例子:

Consumer<Byte> consumer = new Consumer<>();
consumer.accept(data[11]);

我搜索了Func&lt;&gt;Action&lt;&gt;,但我不知道。

Consumer.accept()接口的原始Java代码非常简单。但不适合我:

void accept(T t);

/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation.  If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
}

【问题讨论】:

  • 这是java代码,我们是c#程序员,这个接口对我们来说并不简单:)这个coser做什么?
  • 任何接受一个参数但不返回值的委托类型都是候选类型。 Action&lt;T&gt; 就是其中之一。
  • 谢谢丹尼斯,但我怎样才能替代接受方法?
  • 您在寻找什么?这个问题没有任何意义。有 lambdas、回调、Observables、LINQ 所有这些都可以做任何你使用Consumer.accept 的事情
  • @PanagiotisKanavos action.Invoke(parameter)consumer.accept(parameter) 相同。他们只是给了他们不同的名字。但我意识到这不是操作的问题。

标签: java c# consumer


【解决方案1】:

Consumer&lt;T&gt; 对应于Action&lt;T&gt;andThen 方法是一个排序运算符。您可以将andThen 定义为扩展方法,例如

public static Action<T> AndThen<T>(this Action<T> first, Action<T> next)
{
    return e => { first(e); next(e); };
}

【讨论】:

    【解决方案2】:

    "消费者接口表示接受单个操作的操作 输入参数,不返回结果"

    好吧,如果引用自 here 的这句话是准确的,它大致相当于 C# 中的 Action&lt;T&gt; 委托;

    例如这个java代码:

    import java.util.function.Consumer;
    
    public class Main {
      public static void main(String[] args) {
        Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
        c.accept("Java2s.com");
      }
    }
    

    转换为 C# 将是:

    using System;
    
    public class Main
    {
      static void Main(string[] args)
      {
         Action<string> c = (x) => Console.WriteLine(x.ToLower());
         c.Invoke("Java2s.com"); // or simply c("Java2s.com");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2011-01-10
      • 2010-12-07
      • 2010-11-22
      相关资源
      最近更新 更多