2012-12-05 135 views
1

的領域我有4場bool類型:數組類型布爾

private bool f1; 
public bool F1 { 
get{return this.f1;} 
set 
{ 
this.f1=value; 
onPropertyChanged("F1"); 
} 
} 

private bool f2; 
public bool F2 { 
get{return this.f2;} 
set 
{ 
    this.f2=value; 
    onPropertyChanged("F2"); 
} 
} 
private bool f3; 
public bool F3 { 
get{return this.f3;} 
set 
{ 
this.f3=value; 
onPropertyChanged("F3"); 
} 
} 
private bool f4; 
public bool F4 { 
get{return this.f4;} 
set 
{ 
    this.f4=value; 
    onPropertyChanged("F4"); 
} 
} 

其中只有一個可以實現的。我想要一種方法將它們設置爲for循環。我試過如下:

bool[] myFields = 
{ 
    F1,F2,F3,F4 
}; 

int Answer = 1; 
for (int index = 0; index < myFields.Length; index++) 
{ 
    if(index == Answer) 
    { 
     myFields[index] = true; 
    } 
    else 
    { 
     myFields[index] = false; 
    } 
} 

但這只是myFields數組中的值設置爲true/false和not屬性F2本身。關於如何使這個更好/工作的任何想法?

+4

我會建議使用枚舉代替。 –

+0

嗨...你能舉個例子嗎? enum如何處理這個問題? – lebhero

+0

我發佈了一個關於枚舉如何處理這個問題的簡短示例。 –

回答

4

我想你不希望自動屬性在這裏。這個怎麼樣:

public bool F1 { 
    get { return myFields[0]; } 
    set { myFields[0] = value; } 
} 
etc... 

順便說一句,你for循環可以簡化爲:

for (int index = 0; index < myFields.Length; index++) { 
    myFields[index] = (index == Answer); 
} 
+0

嗨...我會給它一個嘗試....但我需要註冊onPropertyChanged,然後捕捉myFields的任何更改吧? – lebhero

+0

@lebhero我不明白,你必須提供更多關於你想要做什麼的細節。 –

+0

好吧,我需要設置每次所有的屬性爲false ..只是其中一個應該是真的...所以 而不是這樣做: F1 = false; F2 = true; F3 = False; F4 = false; 我想要在for循環中完成... – lebhero

4

這可能與enum得到更好的處理。這樣,您可以允許F1,F2,F3,F4(和「無」,如果適用)值。這是看起來像什麼:

public enum FValue { None, F1, F2, F3, F4 } 

public class Foo 
{ 
    public FValue Value { get; set; } 
} 
+2

如果(最終)想要設置多個標籤,你也可以使用'[Flags]'標籤用OR或XOR數學表示爲'真'。 –