在 Java 中,Supplier介面表示一個沒有引數和通用回傳值的函式。
Supplier<String> randomPasswordSupplier = () -> "secret";
String randomPassword = randomPasswordSupplier.get();
C# 中是否有與此介面等效的介面?
uj5u.com熱心網友回復:
在 C#(可能還有其他語言)中,這是一個delegate,委托是對具有特定引數串列和回傳型別的方法的參考
表示對具有特定引數串列和回傳型別的方法的參考的型別
您可以像這樣定義自己的委托:
public delegate int Answer();
(這通常在宣告事件處理程式時使用)
單獨這個什么都不做,但是你可以像使用任何其他型別一樣使用它來傳遞對方法的參考,就像這樣
public void PrintAnswer(Answer theAnswer)
{
Console.WriteLine(theAnswer());
// If 'theAnswer' can be null, then you can check for it normally, or use the Invoke method like so
Console.WriteLine(theAnswer?.Invoke());
}
為方便起見,.NET 包含一些預定義的委托型別,即Action是一個沒有回傳值 (void) 和任意數量的引數(最多 16 個)的方法,Func是一個具有回傳型別和任意數量引數的方法(最多 16 個)和最后但并非最不重要的Predicate,它是一種回傳布林值并且只有一個引數的方法(所以簡寫為Func<T, bool>)
在您的情況下,您將希望Func<string>像這樣使用:
Func<string> randomPasswordProvider = () => "sekrit";
var randomPassword = randomPasswordProvider(); // or .Invoke()
請注意,在 C# 中,我們使用粗箭頭 ( =>) 表示匿名方法。您還可以randomPasswordProvider指出“全脂”方法,如下所示:
string GenerateRandomPassword()
{
return "Hello world";
}
// Note the lack of '()', we're not invoking the method, only referencing it
Func<string> randomPasswordProvider = GenerateRandomPassword;
如果你想命名你的委托型別,你可以很容易地這樣做:
public delegate string StringSupplier(); // any name you want
// or, if you want to have it generic:
public delegate T Supplier<out T>(); // the 'out' is not needed but helpful
我在這里做了一個例子
然后,您還可以向自定義委托型別添加擴展方法,以便您可以呼叫Get()而不是呼叫Invoke()或只是呼叫()(但這實際上不是必需的,只是讓它看起來更像您的 Java 示例)
uj5u.com熱心網友回復:
任何delegate帶有“不帶引數,回傳T”簽名的泛型都可以使用。
你可以定義你的:
public delegate T Supplier<out T>(); // out is not mandatory but is helpfull
或者使用System.Func<TResult>標準庫中宣告的。
要呼叫它,您只需使用()運算子:
// Func<string> randomPasswordSupplier = () => "secret";
Supplier<string> randomPasswordSupplier = () => "secret";
stringrandomPassword = randomPasswordSupplier();
uj5u.com熱心網友回復:
正如madreflection已經在評論中指出的那樣,對于大多數情況來說,等價物是Func<TResult>。C# 不為此使用介面,而是使用委托,這實際上是方法的簽名。
您還可以創建自己的委托來執行相同的操作:
public delegate TResult Supplier<TResult>();
這將允許您包含特定的檔案,例如,通用Func委托會令人困惑的地方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/408242.html
標籤:
