我想創建一個在運行時設置的自定義類型的列表。這怎麼可能?創建類型的列表customType
這裏是我的代碼:
Type customType = typeof(string); // or someOtherVariable.GetType();
List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
我想創建一個在運行時設置的自定義類型的列表。這怎麼可能?創建類型的列表customType
這裏是我的代碼:
Type customType = typeof(string); // or someOtherVariable.GetType();
List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found
如果你想要實例一些反映類型的泛型列表,你將不得不使用反射來做到這一點:
var type = typeof(string);
var list = typeof(List<>);
var listOfType = list.MakeGenericType(type);
var instance = Activator.CreateInstance(listOfType);
如何將變量'instance'用作列表,因爲它的數據類型是var? – DrRiisTab
@DrRiisTab - 'var'不是數據類型。這只是一個讓編譯器爲你設置靜態類型的快捷方式。如果要在列表中使用'instance',則必須使用Generic重載:https://msdn.microsoft.com/en-us/library/0hcyx2kd(v=vs.110).aspx –
你不能這樣做這個。泛型集合在編譯時是強類型的。你也許可以發出/ codegen一個新類並在需要時動態編譯它,但這是一個非常不同的問題
或,你可以使用反射。 (我沒有低估這個答案,但我認爲這是別人做的原因。) – phoog
爲什麼不只是添加字符串而不是customType? –
這段代碼沒有意義,你似乎正在創建一個字符串列表。 – Arran
實際上,類型將在運行時設置。例如:輸入customType = someOtherVariable.GetType(); – Abdulla