C# 中设置最低工资的 if 语句
我试图在构造函数中设置一个属性,当输入任何小于该值时,该属性将存储最小值 7.50m。属性已经被声明,我只需要这个 if 语句的帮助,一切都会编译,但是当输入一个值时 < 7.5,它不起作用...
public decimal PayRate
{
get
{
return payRate;
}
set
{
if (value <= 7.50m)
payRate = 7.50m;
else
payRate = value;
}
}
编辑:这是输入值的代码... 编辑2:命名空间声明之后的代码,除了添加属性之外我无法更改任何内容。它没有被格式化。
static void Main(string[] args)
{
Employee e1 = new Employee("Chevy", "Jack", 'A', "987654321", 1.20m); }
以及定义所有内容的命名空间。
public Employee(string lName, string fName, char mi, string ss, decimal pay)
{
firstName = fName;
lastName = lName;
MiddleInitial = mi;
SSN = ss;
payRate = pay;
}
I'm trying to set up a property in a constructor that will store a minimum value of 7.50m when any value less than it is entered. The attributes have already been declared, I just need help with this if statement, everything compiles but when a value is entered < 7.5, it doesn't work...
public decimal PayRate
{
get
{
return payRate;
}
set
{
if (value <= 7.50m)
payRate = 7.50m;
else
payRate = value;
}
}
EDIT: Here's the code that enters the values...
EDIT 2: The code following the namespace declaration, I can't change anything but add a property. It didn't get formatted.
static void Main(string[] args)
{
Employee e1 = new Employee("Chevy", "Jack", 'A', "987654321", 1.20m); }
And the namespace where everything is defined.
public Employee(string lName, string fName, char mi, string ss, decimal pay)
{
firstName = fName;
lastName = lName;
MiddleInitial = mi;
SSN = ss;
payRate = pay;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设你有这样的事情。
当您分配时,这应该可以正常工作
,但如果您分配,
这将不起作用,因为您直接将值分配给私有财产。
设置,则不会调用您的 set 访问器
编辑:如果您在构造函数内 。您可以从构造函数参数中删除工资,并在创建 Employee 实例后对其进行设置。
I assume that you are having something like this.
Which should work fine when you assign
but if you assign
this won't work because you are assigning value directly to private property.
Edit: Your set accessor won't get invoked if you set
inside the constructor. You can remove pay from the constructor argument and set it later once you create an instance of Employee.
您的二传手的设计已损坏。 setter 应该将属性设置为指定的值,或者抛出异常。
你应该写:
Your setter is broken by design. A setter should either set the property to the assigned value, or throw an exception.
You should write: