gpt4 book ai didi

java - Java 8 java.util.function.Consumer<> 的 c# 等价物是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:09:43 25 4
gpt4 key购买 nike

在 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 singleinput 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com