我有一系列列表,我想创建一个方法,该方法将按名称查找列表并返回列表。列表存储在类本身中。
public void AddCord(string cord, string listName)
{
List<String> myShip;
myShip = findListByName(listName);
myShip.Add(cord);
}
请保持代码使用最简单的方法..
尝试这个:
//Create global dictionary of lists
Dictionary<string, List<string> dictionaryOfLists = new Dictionary<string, List<string>();
//Get and create lists from a single method
public List<string> FindListByName(string stringListName)
{
//If the list we want does not exist yet we can create a blank one
if (!dictionaryOfLists.ContainsKey(stringListName))
dictionaryOfLists.Add(stringListName, new List<string>());
//Return the requested list
return dictionaryOfLists[stringListName];
}
Dictionary<string, List<string>> myRecords=new Dictionary<string, List<string>>();
if(!myRecords.ContainsKey("abc"))
{
List<string> abcList=new List<string>();
myRecords.Add("abc", abcList);
}
else
myRecords.["abc"].Add("a");
这是我的答案,在我看来更有趣的一种解决方案:D
class MyList<T> : List<T>
{
static List<object> superlist;
public string name;
~MyList() {
if (superlist != null)
superlist.Remove(this);
}
public MyList(string name)
: base() {
init(name);
}
public MyList(string name, int cap)
: base(cap) {
init(name);
}
public MyList(string name, IEnumerable<T> IE)
: base(IE) {
init(name);
}
void init(string name) {
if (superlist == null)
superlist = new List<object>();
this.name = name;
superlist.Add(this);
}
public static void AddToListByName(T add, string listName) {
for (int i = 0; i < superlist.Count; i++) {
if (superlist[i].GetType().GenericTypeArguments[0] == add.GetType() && ((MyList<T>)(superlist[i])).name == listName) {
((MyList<T>)(superlist[i])).Add(add);
return;
}
}
throw new Exception("could not find the list");
}
}
现在您可以在代码中轻松干净地使用它
MyList<string> a = new MyList<string>("a");
MyList<string> b = new MyList<string>("b");
a.Add("normal add to list a");
MyList<string>.AddToListByName("hello add to a", "a");
MyList<string>.AddToListByName("hello add to b", "b");