目前我正在C#中完成一個大學項目,其中包括將一種形式的代碼轉換爲另一種形式的代碼,其中涉及從許多可用的方法中選擇適當的方法/函數。這裏的問題是,使用任何模式匹配技術來實現這一點,而不是使用許多IF ELSE語句。在C#中使用模式匹配選擇合適的方法
現在我已經完成了這個使用嵌套的IF ELSE語句來填充整個程序,看起來像完成時的幼稚代碼。
當前實現: -
輸入:
//stored in list<string>
get(3 int) //type1
get(int:a,b,c) //type2
get(name) //type3
//list passed to ProcessGET method
使用的if else:
public string ProcessGET(List<string> inputData)
{
foreach(var item in inputData)
{
if (inputData.item.Split('(')[1].Split(')')[0].Contains(':'))
{
return Type2 result;
}
else if (!inputData.item.Split('(')[1].Split(')')[0].Contains(':') && Convert.ToInt32(inputData.item.Split('(')[1].Split(')')[0].Split(' ')[0])>0)
{
return Type1 result;
}
else
{
return Type3 result;
}
}
}
如何,我想這是是這樣的,
/stored in list<string>
get(3 int) //type1
get(int:a,b,c) //type2
get(name) //type3
//list passed to ProcessGET method
public string ProcessGET(List<string> inputData)
{
foreach(var itm in inputData)
{
// call appropriate method(itm) based on type using some pattern matching techniques
}
}
string Method1(var data)
{
return result for type1;
}
string Method2(var data)
{
return result for type2;
}
string Method3(var data)
{
return result for type3;
}
通常我的程序主要爲各種類型的輸入關鍵字,如'get','output','declare'等等等等工作......其中Get被轉換爲Scanf語句,輸出到printf語句等等。 在這種情況下,如果我使用IF ELSE,我的項目充滿了If else語句。我只是開始學習C#,我不知道這樣的事情是否存在(谷歌搜索,但沒有找到我在找什麼),所以任何關於這個問題的幫助將是非常有用的(使用)進一步的發展。
很多預先感謝。
你能告訴我們你得到的實際代碼嗎? Type3(var data)函數''是無效的C#。我很難通過'get(3 int)'來表達你的意思。你在說重載嗎? – Rob
'dynamic'關鍵字作爲返回類型允許您返回任意值。然後你可以檢查你使用'typeof'操作符返回的類型,也許可以嘗試挖掘該材料並查看是否可以在你的案例中使用它。 ('public dynamic ProcessGET()'然後可以毫無問題地返回'Type1','Type2'和'Type3'對象。) –
@Rob - 那些get()輸入方法是我自己定製的語法。 – Unknown