我有10个属性,当每个属性设置时,它会增加变量Value
的值。当Value
的值为10时,应用程序将结束。但是将相同的条件写入这些条件似乎很尴尬:
int Value=0;
int A
{
set
{
a=value;
Value++;
if(Value>10) ... //check here
}
}
int B
{
set
{
b=value;
Value++;
if(Value>10) //check here again
}
}
如何简化检查其价值?
答案 0 :(得分:1)
您可以为Value创建一个私有属性,并在该属性的setter中,如果该值设置为大于10,则退出该应用程序。
private int value=0;
private int a, b;
public int A
{
set
{
this.a = value;
Value++;
}
get { return this.a; }
}
public int B
{
set
{
this.b = value;
Value++;
}
get { return this.b; }
}
private int Value
{
set
{
this.value = value;
if (this.value > 10)
{
// Exit.
}
}
get { return this.value; }
}
答案 1 :(得分:1)
我假设你的属性属于一个类,当计数器命中10时,它还有退出程序的其他职责。如果是这样,我会删除检查计数器并从类中退出应用程序的逻辑。 也许你可以使用一个活动。当Value命中10时(您可以实际设置“10”),将通知此事件的订阅者,但这只是一个简短示例)并退出应用程序。
class YourClass {
public event ValueHandler ValueIs10;
public EventArgs e = null;
public delegate void ValueHandler(YourClass m, EventArgs e);
private int _value=0;
public int Value {
get {return _value;}
private set {
_value=value;
if(_value==10 && ValueIs10 != null) ValueIs10(this, e);
}
}
public int A
{
set
{
a=value;
Value++;
}
}
public int B
{
set
{
b=value;
Value++;
}
}
// ...
}
答案 2 :(得分:0)
private int counter;
private int b;
private int a;
public int A
{
set
{
counter++;
a = value;
CheckCounter();
}
}
public int B {
set
{
counter++;
b = value;
CheckCounter();
}
}
public void CheckCounter()
{
if (counter>10)
{
//Do something
}
}
或使计数器属性..
private int Counter
{
set
{
counter = value;
CheckCounter();
}
get
{
return counter;
}
}
并在递增时使用它。
Counter++;
答案 3 :(得分:0)
来自@Richard和@Emil的答案都是正确的,但是为了使您的代码在未来更加可扩展,最好实现内置的INotifyPropertyChanged interface。
class Data : INotifyPropertyChanged
{
private int _counter = 0;
public event PropertyChangedEventHandler PropertyChanged = (sender, arg) =>
{
// if (_counter > 10) Exit();
// from arg you can know what property is changed
// which is probably used for future
};
private int _number;
public int Number
{
get { return _number; }
set
{
//here is another unclear point in your question
//will the counter increases when setting a.Number = 100
//but it's already 100 before setting
if (_number != value)
{
_number = value;
PropertyChanged(this, new PropertyChangedEventArgs("Number"));
}
}
}
}