gpt4 book ai didi

c# - 如何在 ViewModel 中交换属性值?无法通过 ref

转载 作者:行者123 更新时间:2023-11-30 23:18:54 25 4
gpt4 key购买 nike

我想比较和交换两个 ViewModel 公共(public)属性的值,最好使用如下方法:

void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
}
}

但是由于您不能通过 ref 传递属性,所以我不能在我的 ViewModel 中这样做。

private Int32 max;
public Int32 Max
{
get { return max; }
set
{
SwapIfGreater<Int32>(ref Min, ref Max);
max = value;
OnPropertyChanged("Max");
}
}

private Int32 min;
public Int32 Min
{
get { return min; }
set
{
SwapIfGreater<Int32>(ref Min, ref Max);
min = value;
OnPropertyChanged("Min");
}
}

否则...如果我只是尝试直接在 Min getter 或 setter 中使用“if compare”逻辑,当 Min 更改为大于 Max 的值时,我最终会得到 Min 等于 Max。

编辑:根据有关支持属性的建议,我已将方法修改为:

void SwapIfGreater<T>(ref T lhs, ref T rhs, String otherPropertyName) where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
OnPropertyChanged(otherPropertyName);
}
}

和此的“Min”属性 setter :

    min = value;
SwapIfGreater<Int32>(ref min, ref max, "Max");
OnPropertyChanged("Min");

我错过了什么?这仍然只是在Min大于Max时将Max设置为Min。

编辑:虽然我很想知道我在上面做错了什么,但再次测试了实现我想要复制的交换行为的用户界面后,我意识到这是一个令人讨厌的用户体验,因为用户被迫再次单击两个选择器。如果用户选择的 Min 高于 Max,反之亦然,我将恢复到将 Max 重置为“No Maximum”的原始实现。

最佳答案

您不能通过 ref 传递属性,因为属性被转换为 getter 和 setter 方法。

改用属性的支持字段

SwapIfGreater<Int32>(ref min, ref max);

关于c# - 如何在 ViewModel 中交换属性值?无法通过 ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40566202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com