开发者

Storing variable type and using it to create collections at runtime

I have a project which stores values in SQL and later retrieves them for analysis. To keep track of what kinds of values might be stored, I created a class roughly like this:

private class DataFi开发者_开发百科eld
{
    public string FieldName;
    public string FieldType;
}

When values are being read for analysis, a switch statement is used as follows (simplified):

switch (DataField.FieldType)
{
    case "int":
        List<int> InputData = new List<int>();
        // Populate list from DB
    break;
    case "bool":
        List<bool> InputData = new List<bool>();
        // Populate list from DB
    break;
}

Rather than maintain code in multiple places, I am looking for a way to get rid of the switch statement, but that means I need to dynamically create collections based on the type. Current that type is (naively?) a string, but I think I could improve this by changing the class:

private class ImprovedDataField
{
    public string FieldName;
    public Type FieldType;
}

And then dynamically create collections somehow:

Type DataType = typeof(DataField.FieldType);
List<DataType> InputData = new List<DataType>();
// Populate list from DB

This of course does not work, resulting in a Type or namespace name expected error.

Unfortunately I'm not very familiar with working with the Type class, nor generics nor anonymous types as I search for a solution (nothing seems to be appropriate).

How can I reduce duplication of code where the only difference in each switch statement branch is the type of variable collection being produced?


If you want to create statically-typed collection of objects of type known at runtime, you need to use reflection. See i.e. this blog entry - that's the solution for creating List<T>:

public static IList CreateGenericList(Type collectionType)
{
    var listType = typeof(List<>).MakeGenericType(new[] { collectionType});
    return (IList) Activator.CreateInstance(listType);
}

So in your example:

Type dataType = DataField.FieldType;
IList inputData = CreateGenericList(dataType);
// Populate list from DB


Why do you need a typed collection? Why not to use an ArrayList?

ArrayList list = new ArrayList()

list.Add( /* value read from database */ )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜