老問題
原來這就是我想實現...如何避免重寫相同的代碼在不同的方法我有現成的抽象類..lets命名的Class1.cs。它包含許多方法的定義。所以現在我已經包含了 一些新功能,需要在Class1類的每個 方法中實現。所以爲前
public void Method_1(string arg1, string arg2) { /* //some code implementation specific to Method_1 */ Dictionary<string, object> dict= new Dictionary<string, object>(); //there can be more or less arguments in other methods dict.Add("Arg1", arg1); dict.Add("Arg2", arg2); Method_2(dict); }
我必須做同樣的事情在所有的方法,但 可以改變的參數。所以字典對象可以有「n」個參數。有 的方式,我能避免增加相同的代碼 重複的手工勞動(也許使用設計模式如果可能的話)
我想我不明白...捆綁了字典生成 機制不我關心的,我仍然需要添加相同的代碼 在所有的方法(約50)..我正在試圖避免手動一再50次調用 相同的代碼...
編輯並重提問題
我有fina lly決定用一種私人方法建立字典,並用其他所有方法調用它。請在本段之前忽略其他所有內容。 我的方法看起來像這樣
public void Method1(string a, string b , string c)
{
Dictionary<string,object> dict = BuildDictionary(new {a, b ,c});
/*the dict object should have the following structure
key=a, value= value of a
key =b , value = value of b
key =b , value = value of b*/
}
public void Method2(string x, string y)
{
Dictionary<string,object> dict = BuildDictionary(new {x,y});
/*the dict object should have the following structure
key= x, value= value of x
key =y , value = value of y */
}
private Dictionary<string,object> BuildDictionary(params object[] values)
{
//values.ToString() gives = { a= "Value of a", b== "Vaue of b", c= "Value of c"}
//Copy pasting Simon's Code here(use of anonymous objects)
var dictionary = values.GetType()
.GetProperties()
.ToDictionary(pi => pi.Name, pi => pi.GetValue(values));
//this dictionary object gives me a count of 7 with keys as the properties of the object datatype(which is not relevant to my case).
}
所以我需要什麼樣的變化做出的BuildDictionary方法,以獲得所需的字典結構?
你如何在Method_2中使用字典?這可能有助於將簽名更改爲該方法以簡化流程。鑰匙是否遵循一種模式(即ArgN),或者這僅僅是爲了演示的目的? –
歡迎來到「循環」的美好世界! – Tdorno
@SimonBelanger:我編輯了這個問題.....捆綁字典生成機制不是我關心的問題,我仍然需要在所有方法中添加相同的代碼(大約50)..我試圖避免手動一次又一次地調用相同的代碼50次... – blank