Java 8 java.util.function.Consumer 的 c# 等效项是什么<>?

2022-09-04 19:34:18

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

例:

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

我四处寻找,但我不知道。Func<>Action<>

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

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

答案 1

“使用者接口表示接受单个输入参数且不返回任何结果的操作”

好吧,如果上面从这里引用的引用是准确的,它大致相当于C#中的委托;Action<T>

例如,这个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");
  }
}

答案 2

Consumer<T>对应于 并且该方法是排序运算符。您可以定义为扩展方法,例如Action<T>andThenandThen

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

推荐