我做了一個小程式,想分析語料庫中德語名詞的性別。為此,我創建了一些以字串作為回傳值的方法。例如,我想檢查語料庫中名詞前面是否有定語,看它是否包含“der”、“die”或“das”。深化它回傳不同的值。如下所示:
private string definitearticle()
{
// code, where gender is the string which we return - if we can't determine
// the gender it returns "Cannot determine"
return gender;
}
private string indefinitearticle()
{
// code, where gender is the string which we return - if we can't determine
// the gender it returns "Cannot determine"
return gender;
}
我想一個一個地回圈每個方法,直到我不再得到“無法確定”作為回傳值,如下所示,并帶有指向方法的指標串列(如在 C# 中存盤方法串列):
var methods = new List<(System.Action check, string caption)>()
{
(definitearticle, "Definite article"),
(indefinitearticle, "Indefinite article"),
};
foreach (var method in methods)
{
gender = method.check.Invoke();
if (gender != "Cannot determine")
{
// store the outcome that was returned to a list
break;
}
}
問題是我不知道如何使用List具有methodsa 的 a return value(在本例中為 a string)。有人可以幫我嗎?
uj5u.com熱心網友回復:
如果您需要將方法存盤為具有回傳值的型別,則應使用Func<TResult>而不是Action. 它的作業方式與操作相同,只是您可以額外輸入回傳型別作為最后一個泛型型別。因此,例如,如果你有一個方法,它有兩個引數,型別為int和bool,回傳型別為string,你會說
var myReturnMethod = new Func<int, bool, string>((intVal, boolVal) => intVal.ToString() boolVal.ToString());
在您的情況下,只需用以下代碼替換您的方法變數初始化:
var methods = new List<(Func<string> check, string caption)>
{
(definitearticle, "Definite article"),
(indefinitearticle, "Indefinite article"),
};
編輯:
根據 OP 的要求,如果您只希望它包含方法的集合而沒有標題,那么您將如何初始化方法變數:
var methods = new List<Func<string>>
{
definitearticle,
indefinitearticle,
};
更多關于函式的資訊可以在官方微軟檔案中找到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413354.html
標籤:
