2011-10-20 66 views
0

说我有一些属性如何创建一个计算属性

public int redBalls { get; set; } 
public int blueBalls { get; set; } 

我现在想有一个totalBalls财产,将增加两个。

,我会这样做吗?

public int totalBalls { get { return redBalls + blueBalls; } } 

我想这一点,但结果是0

*编辑,我已经说出我的主要开发者,它是因为无论访问totalBalls不通知的redBalls或blueBalls的变化,使它不会重新计算这些值

所以我必须做OnPropertyChanged("total")

+1

你真的设置了'redBalls'和'blueBalls'吗? –

+0

一切都很好,看起来像两个红色/蓝色球0 – sll

+1

'redBalls'和'blueBalls'都不是零,而不是对方的反转,对不对? –

回答

0

没有什么不对您的代码,除了属性名的大小写,这是纯粹的化妆品。

totalBalls将= 0同时的redBallsblueBalls的总和为0,很明显,他们都将= 0,直到它们被设定为其他值。

编辑

你没有提到DependecyProperty S IN的OP或标签,如果dependecy属性绑定到totalBalls财产也不会知道totalBalls从其他属性计算。

,以便其元数据包括PropertyChangedCallback可以检测聚集的变化,而不是你简单的类联接到WPF你应该延长您的依赖项属性的定义。

+1

我认为根据使用情况不需要** Total **属性。 –

+0

@Ramhound - 同意。除非有理由让红色/蓝色球私密并提供总计,否则目前是膨胀的。 – Didaxis

+0

不要担心膨胀,这只是我给你描述的问题,而不会粘贴太多不相关的代码。 –

0

您必须设置实际上可以redBalls/blueBalls的价值

class Balls 
{ 
    public int redBalls { get; set; } 
    public int blueBalls{ get; set; } 

    public int totalBalls{ get{ return redBalls + blueBalls; } } 
} 

void test() 
{ 
    // You must acutally set the value of redBalls/blueBalls 
    var balls = new Balls{ redBalls = 1, blueBalls = 2 }; 
    Assert.AreEqual(3, balls.totalBalls); 
} 
1

写了一个测试你...这个成功对我来说。

[Test] 
public void SO() 
{ 
    var testing = new Testing(); 
    Assert.AreEqual(0, testing.RedBalls); 
    Assert.AreEqual(0, testing.BlueBalls); 
    Assert.AreEqual(0, testing.TotalBalls); 

    testing.RedBalls = 2; 
    testing.BlueBalls = 4; 
    Assert.AreEqual(2, testing.RedBalls); 
    Assert.AreEqual(4, testing.BlueBalls); 
    Assert.AreEqual(6, testing.TotalBalls); 
} 

class Testing 
{ 
    public int RedBalls { get; set; } 
    public int BlueBalls { get; set; } 
    public int TotalBalls { get { return RedBalls + BlueBalls; } } 
} 
+0

谢谢,我遇到的问题是绑定时。 –