将字符串转换为数据类型并在 C# 中创建泛型列表

Transform string to datatype and create generic list in C#

我尝试创建一个具有不同数据类型的通用列表。

比如我有一个字符串数组:

string[] stringArray = new string[] {"integer", "double"};

并且我想创建一个包含字符串中给定类型的列表。 例如:

List<stringArray[0]> intList = new List<stringArray[0]>();

但这不起作用。

有谁知道如何做到这一点不用 if 语句

编辑: 我只想用一个循环创建不同类型的不同列表。在我的示例中,将有 2 个列表(int 和 double)。如果还有另一个元素,例如称为 bool。将有三个列表(一个 int 列表,一个 double 列表和一个 bool lost)

像这样的东西会起作用:

        string[] stringArray = new string[] { "System.Int32", "System.Double" };
        List<object> intList = new List<object>();

        foreach (string tipo in stringArray)
        {
            try
            {
                intList.Add(Activator.CreateInstance(Type.GetType(tipo)));
            }
            catch (TypeLoadException e)
            {
                Console.WriteLine("{0}: Unable to load type", e.GetType().Name);
            }
        }

但请记住,字符串必须是完全限定类型(如“System.Int32”)

如果您只需要类型列表,请省略 Activator.CreateInstance()

List<Type> 会是更好的选择。下面的示例创建了一个 Type 的集合,然后遍历该集合,为每个项目创建一个新实例。

// Generic List
var types = new List<Type>();

// Add Types
types.Add(typeof(int));
types.Add(typeof(double));

// Iterate List
foreach(var type in types)
{
    // Dynamically create instances of type
    var instance = Activator.CreateInstance(type);

    // Insert additional code
}