示例代碼:重構將NameValueCollection和KeyValueConfigurationCollection作爲參數?
EDITED:澄清的示例。對不起,有任何困惑。
using System.Collections.Specialized;
using System.Configuration;
...
// get collection 1
NameValueCollection c1 = ConfigurationManager.AppSettings;
// get collection 2
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "c:\\SomeConfigFile.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
KeyValueConfigurationCollection c2 = config.AppSettings.Settings;
// do something with collections
DoSomethingWithCollection(c1);
DoSomethingWithCollection(c2);
...
private void DoSomethingWithCollection(KeyValueConfigurationCollection c)
{
foreach(KeyValueConfigurationElement el in c)
{
string key = el.Key;
string val = el.Value;
// do something with key and value
}
}
private void DoSomethingWithCollection(NameValueCollection c)
{
for(int i=0; i < c.Count; i++)
{
string key = c.GetKey(i);
string val = c.Get(i);
// do something with key and value
}
}
目前DoSomethingWithCollection的兩個版本採取任何一個的NameValueCollection或KeyValueConfigurationCollection。
有沒有更乾淨的方式做到這一點,所以只有一個版本的DoSomethingWithCollection?
謝謝。
我刪除了我的編輯「不需要一個代表」的一部分 - 我誤會了你試圖做。從這裏的答覆看來,這兩種類型之間沒有足夠的共同點來做出簡單的解決方案。不過謝謝你的努力。 – 2010-08-24 07:47:33