[英]Return different list types C#
試圖弄清楚如何返回不同的列表類型。
嘗試這樣的事情,但似乎不起作用:
public Dictionary<string,object> Data;
public List<T> ReturnList(string key){
var type = Data[key].GetType().Name;
switch(type){
case "Bool":
return new List<bool>(); break;
case "Int":
return new List<int>(); break;
case "String":
case default:
return new List<string>(); break;
}
return null;
}
有人知道這怎么可能嗎?
注意:我是C#新手
您可以返回IList
而不是List<T>
。 我已經重新定義了您的ReturnList ,現在看起來像這樣-
public IList ReturnList(string key)
{
//var type = Data[key].GetType().Name;
switch (key)
{
case "System.Boolean":
return new List<bool>(); break;
case "System.Int32":
return new List<int>(); break;
case "System.String":
return new List<string>(); break;
}
return null;
}
在這里,我假設您的字典包含這樣的值-
var dict = new Dictionary<string, object>()
{
{"bool", typeof(bool)},
{"string", typeof(string)},
{"Int", typeof(int)}
};
您可以根據需要修改功能。
我已經在.Net Fiddle控制台應用程序中對此進行了測試-
var type = dict["bool"].ToString();
Program prg = new Program();
var list = prg.ReturnList(type);
Console.WriteLine(list);
這是一個有點奇怪的問題,但我認為這將解決問題:
public List<T> ReturnList<T>(string key){
if (Data[key].GetType() != typeof (T))
{
throw new Exception("Invalid data type for key");
}
return new Lit<T>();
}
仍然進行了類型檢查,但使用了通用方法的所有優點。
您不需要在return語句之后寫case和默認情況前寫case的 break 。 同樣,布爾類型的名稱是“ Boolean”,而int實際上是“ Int32”。
public static IList ReturnList(string key)
{
var type = Data[key].GetType().Name;
switch(type){
case "Boolean":
return new List<bool>();
case "Int32":
return new List<int>();
case "String":
default:
return new List<string>();
}
return null;
}
例:
Data = new Dictionary<string, object>();
Data.Add("someBool", true);
Data.Add("someInt", 42);
Data.Add("someString","test");
IList listString = ReturnList("someString");
IList listInt = ReturnList("someInt");
IList listBool = ReturnList("someString");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.