存储变量类型并在运行时使用它来创建集合 [英] Storing variable type and using it to create collections at runtime
问题描述
我有一个项目,它在 SQL 中存储值,然后检索它们进行分析.为了跟踪可能存储的值类型,我创建了一个大致如下所示的类:
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 DataField
{
public string FieldName;
public string FieldType;
}
当读取值进行分析时,switch 语句的使用如下(简化):
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;
}
我不是在多个地方维护代码,而是在寻找一种摆脱 switch 语句的方法,但这意味着我需要根据类型动态创建集合.当前该类型是(天真地?)一个字符串,但我认为我可以通过更改类来改进这一点:
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.
不幸的是,在我寻找解决方案时,我对使用 Type
类、泛型或匿名类型不太熟悉(似乎没有什么合适的).
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).
如何减少代码重复,其中每个 switch 语句分支的唯一区别是生成的变量集合的类型?
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);
}
所以在你的例子中:
Type dataType = DataField.FieldType;
IList inputData = CreateGenericList(dataType);
// Populate list from DB
这篇关于存储变量类型并在运行时使用它来创建集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!