2016-04-06 56 views
6

在C#中有這個接口的等價物嗎?什麼是Java 8 java.util.function.Consumer <>的c#等價物?

例如:

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

找遍周圍Func鍵<>和行動<>,但我不知道....

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

這是Java代碼,我們是C#程序設計師和這個接口不是簡單的給我們:)啥子這個消費者呢? –

+2

任何接受一個參數且不返回值的委託類型都是候選人。 '行動'是其中之一。 –

+0

非常感謝丹尼斯,但我該如何取代接受方法? –

回答

6

「消費者接口表示接受單個 輸入參數,並返回無結果的操作」

那麼,如果此引自here採取準確那麼它是等效Action<T>代表在C#;

例如,這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"); 
    } 
} 
1

Consumer<T>對應Action<T>andThen方法是一個測序算子。您可以將andThen定義爲擴展方法,例如

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