How get value without downcast? C#

Viewed 38

Base class for setting. It helps generate settings without class with settings

{
    public SettingViewModel(string title)
    {
        Title = title;
    }
    public string Title { get; set; }
    protected Control _control = new();
    public Control Control
    {
        get => _control;
    }
}

Example class for one type setting

public class TextboxSettingViewModel : SettingViewModel
{
    public TextboxSettingViewModel(string title, double value) : base(title)
    {
        _control = new TextBox();
        _value = value;
        var binding = new Binding("Value") { Source = this };
        _control.SetBinding(TextBox.TextProperty, binding);
    }

    private double _value;

    public double Value
    {
        get { return _value; }
        set { _value = value; }
    }
}

How take value without downcasting? I'm don't want use Reflection.

public List<SettingViewModel> Settings { get; set; } = new();
public MainWindow()
{
    Settings.Add(new TextboxSettingViewModel("Hello, world", 25));
    // If need get setting need do downcast
    if (Settings[0] is TextboxSettingViewModel)
    {
        double a = (Settings[0] as TextboxSettingViewModel).Value;
    }
}
0 Answers
Related