如何使用变量值创建参数类

时间:2013-08-21 22:43:27

标签: c# .net generics properties

我想创建一个params集合。使用泛型创建集合非常简单:

List<Param> Params = new List<Param>();

我可以简单地添加这样的参数:

List<Param> Params = new List<Param>() {
    new Param() { Label = "Param 1", Type = Param.ParamType.Text },
    new Param() { Label = "Param 2", Type = Param.ParamType.Select }
}

现在,如何为每个参数添加一个类型值属性?

像:

  • 文字的字符串
  • 选择
  • 的选项列表
  • 日期,布尔......

我认为有更好的解决方案:

new Param() { Label = "Param 1", Type = Param.ParamType.Text, StringValue = "text" },
new Param() { Label = "Param 1", Type = Param.ParamType.Text, StringValue = "text" },
new Param() { Label = "Param 1", Type = Param.ParamType.CheckBox, BoolValue = true }

1 个答案:

答案 0 :(得分:0)

我建议创建一个通用子类:

public Param<T> : Param
{
    public T Value { get; set; }
}

然后像这样创建它们:

new Param<string>() { Label = "Param 1", Type = Param.ParamType.Text, Value = "text" },
new Param<string>() { Label = "Param 1", Type = Param.ParamType.Text, Value = "text" },
new Param<bool>() { Label = "Param 1", Type = Param.ParamType.CheckBox, Value = true }

您可以利用类型推断在Param上创建更方便的静态方法:

public class Param 
{
    ...
    public static Param<T> From<T>(string label, ParamType type, T value)
    {
        return new Param<T>() 
        {
            Label = label, 
            Type = type, 
            Value = value 
        }
    }
}

然后像这样使用它:

Param.From("Param 1", Param.ParamType.Text, "text"),
Param.From("Param 1", Param.ParamType.Text, "text"),
Param.From("Param 1", Param.ParamType.CheckBox, true)
相关问题