简体   繁体   中英

How to create a parameter class with variant value

I want to create a params collection. 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?

Like:

  • a string for the text
  • an options list for the select
  • a date, a boolean…

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM