![](/img/trans.png)
[英]Error passing in func<type, bool> as a parameter to an async method
[英]Passing parameter to a method and assigning to type Func<bool>
我目前有一個類似的方法
public static bool test(string str);
我想將此方法分配給這種類型
Func<bool> callback
我正在嘗試這樣做(這是不正確的)
callback = test("Str");
以上是不正確的,因為 C# 我正在調用一個方法。 如何告訴它使用參數 Str 調用該方法? 在 C++ 我們可以做到這一點
std::function<...,..,"str">
我們如何在 C# 中做類似的事情?
如果您的目標是始終使用相同的字符串參數(而不是每次都使用不同的參數)調用回調,您可以將其聲明為:
Func<bool> callback = () => test("Str");
var result = callback();
但是,如果您打算每次傳遞不同的字符串值,那么您需要一個Func<string, bool>
:
Func<string, bool> callback = s => test(s);
var result = callback("Str");
您應該將 function 聲明為:
Func<string, bool> callback
指示它引用的方法使用一個string
並返回一個bool
。
然后稍后您可以執行以下操作:
callback = s => test(s);
或內聯:
Func<string, bool> callback = s => test(s);
讓我看看我是否知道你在說什么。 在 C++ 中,我們有“函數指針”,它們用特定的簽名聲明。 要使 C# 中的等效項使用委托關鍵字。
這是一個快速的功能代碼示例:
class DelegateExample
{
// A delegate is a prototype for a function signature.
// Similar to a function pointer in C++.
delegate bool MyDelegate(string[] strings);
// A method that has that signature.
bool ListStrings(string[] strings)
{
foreach (var item in strings)
{
Console.WriteLine(item);
}
return strings.Length > 0; // ... for example
}
// Different method, same signature.
bool Join(string[] strings)
{
Console.WriteLine(string.Join(", ", strings));
return strings.Length > 0; // ... for example
}
public void TryIt()
{
string[] testData = { "Apple", "Orange", "Grape" };
// Think of this as a list of function pointers...
List<MyDelegate> functions = new List<MyDelegate>();
functions.Add(ListStrings); // This one points to the ListStrings method
functions.Add(Join); // This one points to the Join method
foreach (var function in functions)
{
bool returnVal = function(testData);
Console.WriteLine("The method returned " + returnVal + Environment.NewLine);
}
}
}
您可以像這樣在控制台應用程序中運行示例:
class Program
{
static void Main(string[] args)
{
new DelegateExample().TryIt();
Console.ReadKey();
}
}
這給出了這個 output:
Apple
Orange
Grape
The method returned True
Apple, Orange, Grape
The method returned True
希望這會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.