c# - 如何在不指定类型的情况下将泛型类存储在列表中?

标签 c# .net list generics

我有以下类(class):

class Parameter<T>
{
    public string Index { get; set; }
    public T Value { get; set; }
}

我想要一个这样的列表:

class ParameterModel
{
    public List<Parameter<>> Parameters {get;}
}

然后我会有这样的代码:

...
Parameter<> parameter = parameterModel.Parameters.Where(p => p.Index == "AAA");
if (parameter is Parameter<bool>)
{
    ...
}
else if (parameter is Parameter<int>)
{
    ...
}
...

这是可行的还是我应该使用继承而不是泛型?

提前致谢。

最佳答案

不会

class ParameterModel<T>
{
    public List<Parameter<T>> Parameters { get; }
}

做这份工作?


或者您可能不需要不同类型的参数?那么你可以做

public interface IParameter
{
    string Index { get; set; }
    Type ParameterType { get; }
}

public class Parameter<T> : IParameter
{
    public string Index { get; set; }
    public T Value { get; set; }
    public Type ParameterType
    {
        get
        {
            return typeof(T);
        }
    }
}

class ParameterModel
{
    public List<IParameter> Parameters { get; }
}

所以你可以这样做,

var aaaParameter = parameterModel.Parameters.Single(p => p.Index == "AAA");
if (aaaParameter.ParameterType == typeof(bool))
{
    ...
}
else if (aaaParameter.ParameterType == typeof(string))
{
    ...
}

但是,考虑到您描述的问题的范围,一个简单的字典可能是最好的。

var parameterModel = new Dictionary<string, object>();

允许

var aaaParameter = parameterModel["AAA"];
if (aaaParameter is bool)
{
    ...
}
else if (aaaParameter is string)
{
    ...
}

关于c# - 如何在不指定类型的情况下将泛型类存储在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18911879/

相关文章:

c# - 如何适本地从字符串中获取字节?

c# - 按比例收集值(value)

c# - 如何确定 "ConfigurationElement"在 "ConfigurationSection"自定义配置设置上可用

python - 如何按索引对列表进行分组?

c# 列出组合框中变量字符串中的所有出现情况

c# - 在 C# 中使用枚举值反序列化 Dictionary<string, object>

c# - 未应用 Wpf 按钮样式

c# - 将整数转换为货币

C#。如何以编程方式从控制台应用程序中选择和复制文本?

java - 奇怪的行为: Java Comparator randomizes list entries