在 C# 中是否有此接口(interface)的等效项?
示例:
Consumer<Byte> consumer = new Consumer<>();
consumer.accept(data[11]);
我搜索了 Func<>
和 Action<>
但我不知道。
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); };
}
最佳答案
"Consumer interface represents an operation that accepts a single input argument and returns no result"
好吧,前提是上面的引述来自 here是准确的,它大致相当于 Action<T>
在 C# 中委托(delegate);
例如这个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");
}
}
关于java - Java 8 java.util.function.Consumer<> 的 c# 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449343/