在Java中,Supplier接口表示没有参数和泛型返回值的函数。
Supplier<String> randomPasswordSupplier = () -> "secret";
String randomPassword = randomPasswordSupplier.get();在C#中有与此接口相当的接口吗?
发布于 2022-01-11 10:45:00
在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包括一些预定义的委托类型,即动作,它是一种没有返回值的方法(void)和任意数量的参数(最大为16),漏斗是一种具有返回类型的方法和任意数量的参数(最多为16),最后但并非最不重要的是,谓词是一种返回布尔值的方法,它只有一个参数(因此是Func<T, bool>的缩写)。
在您的例子中,您需要像这样使用Func<string>:
Func<string> randomPasswordProvider = () => "sekrit";
var randomPassword = randomPasswordProvider(); // or .Invoke()注意,在C#中,匿名方法使用fat箭头(=>)。您还可以让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()或() (但这并不是必要的,只是让它看起来更像您的Invoke()示例)
发布于 2022-01-11 10:22:24
任何带有“不带参数,返回delegate”签名的通用T都可以工作。
你可以定义你的:
public delegate T Supplier<out T>(); // out is not mandatory but is helpfull或者使用标准库中声明的System.Func。
要调用它,只需使用()操作符:
// Func<string> randomPasswordSupplier = () => "secret";
Supplier<string> randomPasswordSupplier = () => "secret";
stringrandomPassword = randomPasswordSupplier();https://stackoverflow.com/questions/70665003
复制相似问题