让两个变量相互镜像

本文关键字:变量 镜像 两个 | 更新日期: 2023-09-27 18:29:37

class InputBox : TextBox
{
    private object value;
    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);
        try
        {
            value = TypeDescriptor.GetConverter(value.GetType()).ConvertFromString(Text);
        }
        catch (Exception e1)
        {
            Utils.offensiveMessage("Invalid format! This field accepts only " + value.GetType().Name + "!");
            Focus();
            Text = value.ToString();
        }          
    }
    public InputBox(object value) : base()
    {
        this.value = value;
        initializeComponent();
    }
    private void initializeComponent()
    {          
        Text = value.ToString();
    }
}

这里的此类将对象作为输入,将其表示为字符串,然后确保文本框中写入的任何内容保持相同的类型。它可以处理的类型(仅限值类型(有限制,但我正在这些范围内工作。我为什么需要这个?

我有一个大类,它有很多子类,最后都包含值类型。我想要的是将这些数据呈现给用户并让他能够对其进行编辑。这是我的UI的一个原子。

这里很棒的是让我在我的大类中的变量被上面显示的类中的变量镜像的方法。当我在小班里换一个时,大班班里的那个也会以同样的方式改变。

我该怎么做?

让两个变量相互镜像

我会考虑使用 Winforms 数据绑定 - 如果您支持大型类上的 INotifyPropertyChanged,它已经通过双向通知执行此操作。

但是,如果出于某种原因不想使用数据绑定,则可以将其视为仅使代码正常工作的替代方法:

public static class Program
{
    public static void Main()
    {
        var largeClass = new LargeClass() { Blah = 423 };
        var inputBox = new InputBox<double>(
            () => largeClass.Blah, 
            (a) => largeClass.Blah = a
            );
    }
}
public class LargeClass
{
    public double Blah { get; set; }
}
public class InputBox<T> : TextBox
{
    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);
        try
        {
            _setter((T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(Text));
        }
        catch (Exception e1)
        {
            //Utils.offensiveMessage("Invalid format! This field accepts only " + value.GetType().Name + "!");
            Focus();
            Text = _getter().ToString();
        }
    }
    private Func<T> _getter;
    private Action<T> _setter;
    public InputBox(Func<T> getter, Action<T> setter) : base()
    {
        _getter = getter;
        _setter = setter;
        InitializeComponent();
    }
    private void InitializeComponent()
    {
        Text = _getter().ToString();
    }
}

我最终创建了一个实现观察者模式类型接口的包装器。

包装对象确保甚至值类型作为引用传递(因为我现在传递的是包装器而不是值(。

我设置了观察者模式,以便观察到的包装对象可以通知任何观察者,然后观察者会相应地更新。