[英]How to create a parameter class with variant value
I want to create a params collection. 我想创建一个params集合。 Create a collection with generics is very simple: 使用泛型创建集合非常简单:
List<Param> Params = new List<Param>();
And I can simply add params like this: 我可以简单地添加如下参数:
List<Param> Params = new List<Param>() {
new Param() { Label = "Param 1", Type = Param.ParamType.Text },
new Param() { Label = "Param 2", Type = Param.ParamType.Select }
}
Now, how do I add a typed value property for each param? 现在,如何为每个参数添加类型化的value属性?
Like: 喜欢:
I think there are a better solution like that: 我认为有这样一个更好的解决方案:
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 }
I'd recommend making a generic subclass: 我建议制作一个通用子类:
public Param<T> : Param
{
public T Value { get; set; }
}
And then create them like this: 然后像这样创建它们:
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 }
You can take advantage of type inference to create a more convenient static method on Param
: 您可以利用类型推断在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
}
}
}
And then use it like this: 然后像这样使用它:
Param.From("Param 1", Param.ParamType.Text, "text"),
Param.From("Param 1", Param.ParamType.Text, "text"),
Param.From("Param 1", Param.ParamType.CheckBox, true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.