0

想象一下我有这门课:

Class Foo
{
    public Bar b1 { get; set; }
    public Bar b2 { get; set; }
    public Bar b3 { get; set; }

    public void UpdateBarsMyProp(bool value)
    {
        // ????
    }
}

Class Bar
{
    public bool MyProp { get; set; }

    public bool UpdateMyProp(bool value)
    {
        this.MyProp = value;
    }
}

更新 b1、b2 和 b3 中的属性 MyProp 的最佳方法是什么?

泛型?

代表?

编辑:

只是为了添加有关我的具体情况的更多信息:

我正在创建一个虚拟键盘,我正在使用 WPF MVVM,所以我有:

一个包含多个 Key ViewModel 的 KeyBoard ViewModel,我无法将它们存储在 List 中,因为我的 View(xaml 文件)需要将每个关键信息绑定到特定的 ViewModel。

现在,当用户按下虚拟 shift 按钮时,我需要我的 Keyboard ViewModel 对象来更新每个 Key ViewModel 中的显示字符。

4

4 回答 4

2

你可以把你的属性放在一个List<Bar>(或者如果你喜欢的话是一个数组......)并对其进行迭代。

所以:

public Bar b1 { get; set; }
public Bar b2 { get; set; }
public Bar b3 { get; set; }
// other Bar props...

private List<Bar> barsList = new List<Bar>(){ b1, b2, b3, ... };

public void UpdateBarsMyProp(bool value)
{
    foreach(Bar bar in barsList)
    {
        bar.MyProp = value;
    }
}
于 2012-08-31T10:13:07.270 回答
0

也许您的示例已简化,但为什么不这样做

b1.MyProp = b2.MyProp = b3.MyProp = value;

另外,为什么要打扰这种UpdateMyProp方法?这与您拥有的属性设置器方法相同。如果您需要向 setter 添加更多逻辑,可以通过更改来停止使用自动实现的属性

public bool MyProp { get; set; }

private bool myProp;

public bool MyProp
{
   get { return this.myProp; }
   set
   {
      // any logic here
      this.myProp = value;
   }
}
于 2012-08-31T10:08:12.213 回答
0

如果您的所有条形对象都需要相同的 MyProp,您可以将 MyProp 设置为静态:

public static bool MyProp { get; set; }

然后,您可以使用以下命令编辑所有 bar 对象的所有 MyProps:

Bar.MyProp = baz;

仅当所有 Bar 对象共享相同的 MyProp 时才使用此选项

于 2012-08-31T10:11:14.420 回答
0

你可能想要这样的东西。

class Foo
{
    private readonly IList<Bar> bars = new List<Bar>
        {
            new Bar(),
            new Bar(),
            new Bar()
        }

    public Bar this[int i]
    {
        get
        {
           return this.bars[i];
        }
    }

    public void UpdateBars(bool value)
    {
        foreach (var bar in this.bars)
        {
            bar.MyProp = value;
        }
    }
}

然后您可以像这样访问第一个栏

var foo = new Foo();
var firstBar = foo[0];

您可以使用一个小转换器绑定到索引器,这将使您的模型不那么脆弱。


如果您不想使用索引器,则可以将 setter 提高到Foo.

Class Foo
{
    public Bar b1 { get; set; }
    public Bar b2 { get; set; }
    public Bar b3 { get; set; }

    public bool MyProp
    {
        set
        {
            if (this.b1 != null)
            {
                this.b1.MyProp = value;
            }

            if (this.b2 != null)
            {
                this.b2.MyProp = value;
            }

            if (this.b3 != null)
            {
                this.b3.MyProp = value;
            }
        }
    }
}
于 2012-08-31T10:19:24.863 回答