以下列表是在名为“Entities”的类中创建的,它们是私有的。 我想通过以下方式返回它们(并在另一个类中使用):
public List<string> getCMList()
{
return exceptionsCM;
}
但如果有10个列表,我必须为所有这些列表编写一个公共“获取”方法。是否可以编写一个方法,将字符串作为输入,并返回该列表? 应该是类似的东西..
public List<string> getList(.....)
{
return exceptionCM;
} //if we call getList(exceptionCM).
exceptionsCM = new List<string>();
exceptionsCM.Add("CM12");
exceptionsCM.Add("CM701");
exceptionsCM.Add("CM901/CM30");
exceptionsCM.Add("CM901K");
exceptionsCM.Add("CM1101");
exceptionsCM.Add("CM1101K");
//List with Multi Mill exceptions, they are included in the new MultiB
exceptionsMultiB = new List<string>();
exceptionsMultiB.Add("Multi650/450");
exceptionsMultiB.Add("Multi660/630");
exceptionsMultiB.Add("Multi650/800");
exceptionsMultiB.Add("Multi650/1000");
//List with Multi Mill exceptions, they are included in the new Multi01
exceptionsMulti01 = new List<string>();
exceptionsMulti01.Add("Multi301");
exceptionsMulti01.Add("Multi601");
exceptionsMulti01.Add("Multi801");
exceptionsMulti01.Add("Multi1001");
答案 0 :(得分:2)
您可以为此
使用Dictionary<K,V>
课程
private Dictionary<string, List<<string>> dictionary =
new Dictionary<string, List<<string>>();
//fill that dictionary
...
//get list from a dictionary by list id
public List getList(string listId)
{
return dictionary[listId];
}
答案 1 :(得分:2)
您可以将所有列表放在字典中:
// your code here
dictionary = new Dictionary<string, List<string>>();
dictionary.Add("exceptionsCM", exceptionsCM);
然后getList方法就像:
一样简单public List<string> getList(string name)
{
return dictionary[name];
}
答案 2 :(得分:2)
您可以将它们全部放在静态字典中&gt;像那样
Dictionary<string, List<string>> ListstDict = new Dictionary<string, List<string>>();
ListsDict.Add("exceptionsCM", exceptionsCM);
...
然后你可以写一个像这样的方法:
public List<string> GetList(string name)
{
return ListsDict.ContainsKey(name) ? ListsDict[name] : null;
}
但话又说回来,如果你可以简单地得到它们,那么这个名单的重点是什么呢?将私有setter
声明为公共属性会更容易public List<string> exceptionsCM { get; private set; }
答案 3 :(得分:0)
使用字典和枚举。
将枚举用于列表键而不是字符串可使代码对于键重命名更加健壮。即当您在 Entities 类中将 MultiB 重命名为 MultiB1 时,编译器将不会显示有关GetList(“MultiB”)调用的任何错误和警告。如果使用 enum ,编译器会显示这些错误。
internal class Entities
{
private Dictionary<ListKey, List<string>> _liststDict =
new Dictionary<ListKey, List<string>>
{
{ListKey.Cm, new List<string> {"CM12", "CM701", "CM901/CM30", "CM901K", "CM1101", "CM1101K"}},
{ListKey.MultiB, new List<string> {"Multi650/450", "Multi660/630", "Multi650/800", "Multi650/1000"}},
{ListKey.Multi01, new List<string> {"Multi301", "Multi601", "Multi801", "Multi1001"}}
};
public List<string> GetList(ListKey key)
{
return _liststDict[key];
}
internal enum ListKey
{
Cm,
MultiB,
Multi01
}
}
internal class EntitiesTester
{
public static void Do()
{
Entities entities = new Entities();
Console.Out.WriteLine("CM count = {0}", entities.GetList(Entities.ListKey.Cm).Count);
Console.Out.WriteLine("MultiB count = {0}", entities.GetList(Entities.ListKey.MultiB).Count);
Console.Out.WriteLine("Multi01 count = {0}", entities.GetList(Entities.ListKey.Multi01).Count);
}
}