C# 使用Set validation from属性在构造函数中设置私有字段
所以。。如何使用构造函数中的属性验证私有实例变量(字段) 我有这样的代码,但我有一种强烈的感觉,这不是应该怎么做的:C# 使用Set validation from属性在构造函数中设置私有字段,c#,constructor,properties,C#,Constructor,Properties,所以。。如何使用构造函数中的属性验证私有实例变量(字段) 我有这样的代码,但我有一种强烈的感觉,这不是应该怎么做的: class Account { private decimal acctBalance = 0; public decimal AcctBalance { get { return acctBalance; }
class Account
{
private decimal acctBalance = 0;
public decimal AcctBalance
{
get
{
return acctBalance;
}
set
{
if (acctBalance >= 0)
acctBalance = value;
else
{
Console.WriteLine("Invalid balance, balance set to 0");
acctBalance = 0;
}
}
}
public Account(decimal balance)
{
acctBalance = balance;
AcctBalance = acctBalance;
}
}
我只是想确定这是正确的方法
谢谢 您的方法基本上是正确的,尽管存在一些问题。我修复了它们,并在代码中添加注释
class Account
{
private decimal acctBalance = 0;
public decimal AcctBalance
{
get
{
return acctBalance;
}
set
{
//modified to check value instead of acctBalance
if (value >= 0)
acctBalance = value;
else
{
Console.WriteLine("Invalid balance, balance set to 0");
acctBalance = 0;
}
}
}
public Account(decimal balance)
{
//redundant! Changing AcctBalance changes acctBalance
//acctBalance = balance;
AcctBalance = balance;
}
}
您的方法基本上是正确的,尽管存在一些问题。我修复了它们,并在代码中添加注释
class Account
{
private decimal acctBalance = 0;
public decimal AcctBalance
{
get
{
return acctBalance;
}
set
{
//modified to check value instead of acctBalance
if (value >= 0)
acctBalance = value;
else
{
Console.WriteLine("Invalid balance, balance set to 0");
acctBalance = 0;
}
}
}
public Account(decimal balance)
{
//redundant! Changing AcctBalance changes acctBalance
//acctBalance = balance;
AcctBalance = balance;
}
}
这是一个家庭作业,特别要求我使用公共属性设置私有字段,我只想确保这是正确的方法,或者至少是普遍接受的方法。以下是确切的说明:“基类帐户应包含一个decimal类型的私有实例变量,以表示帐户余额。该类应提供一个构造函数,该构造函数接收初始余额,并使用它初始化具有公共属性的实例变量。属性应验证初始余额,以确保其大于或等于0.0。否则,余额应设置为0.0,设置访问器应显示一条错误消息,指示初始余额无效。“+1用于修复设置器(
value
vs private field name-正如最初编写的那样,它不会达到OP预期的效果)构造器中的冗余:)啊!!!现在一切都有意义了!!我从来没有想过它会这样工作,我知道有更好的方法!非常感谢:)这是一个家庭作业,特别要求我使用公共属性设置私有字段,我只想确保这是正确的方法,或者至少t通常接受的方法这里有确切的说明:“基类帐户应该包括一个decimal类型的私有实例变量来表示帐户余额。该类应提供一个构造函数,该构造函数接收初始余额,并使用它初始化具有公共属性的实例变量。属性应验证初始余额,以确保其大于或等于0.0。否则,余额应设置为0.0,设置访问器应显示一条错误消息,指示初始余额无效。“+1用于修复设置器(value
vs private field name-正如最初编写的那样,它不会达到OP预期的效果)构造器中的冗余:)啊!!!现在一切都有意义了!!我从来没有想过它会这样工作,我知道有更好的方法!非常感谢:)