C# 具有递增一个变量的多个属性。简单检查一下它的价值?
我有10个属性,当每个属性都被设置时,它会增加变量C# 具有递增一个变量的多个属性。简单检查一下它的价值?,c#,variables,properties,C#,Variables,Properties,我有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>
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
}
}
如何简化对其值的检查?您可以为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; }
}
或者把柜台变成一种财产
private int Counter
{
set
{
counter = value;
CheckCounter();
}
get
{
return counter;
}
}
并在递增时使用此选项
Counter++;
@Richard和@Emil的回答都是正确的,但是为了使您的代码在将来更具可扩展性,最好实现内置的
我假设您的属性位于一个类中,该类除了在计数器达到10时退出程序外,还有其他职责。如果是这样,我将删除检查计数器并从类中退出应用程序的逻辑。 也许你可以用一个事件。当值达到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++;
}
}
// ...
}
我知道,我只是想把这个例子简短一点。我已经更新了我的答案,现在加入了getter。在我看来这是最好的答案。虽然其他答案也适用,但这一个设计最好。
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"));
}
}
}
}
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++;
}
}
// ...
}