c# - 变量不保存值
问题描述
我正在尝试创建的程序有问题。这个程序就像一张信用卡,问题是我放入“信用”变量的金额似乎根本不影响该变量,它保持为空。以下是信用卡类:
我已经编辑了代码,因为我刚刚注意到我没有插入所有内容并且还包含了 program.cs!该程序运行时的结果:https ://prnt.sc/jynpt1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardExample
{
public class CreditCard
{
private double credit;
public double Credit
{
get { return credit; }
set { credit = value; }
}
public CreditCard(double credit)
{
this.credit = Credit;
}
public bool enoughCredit (double creditAmt)
{
bool state = false;
if (Credit >= creditAmt)
{
Console.WriteLine("You have sufficient funds.");
state = true;
}
else
{
Console.WriteLine("You do not have sufficient amount");
state = false;
}
return state;
}
public double getAmtInCreditCard()
{
Console.WriteLine("Amount of Money in your CreditCard: ", Credit);
return Credit;
}
}
}
程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditCardExample
{
class Program
{
static void Main(string[] args)
{
CreditCardExample.CreditCard c = new
CreditCardExample.CreditCard(20.0);
c.enoughCredit(12);
c.getAmtInCreditCard();
Console.ReadKey();
}
}
}
解决方案
那是因为在您的构造函数中,您将属性分配回自身,而不是传递的值,即
this.credit = Credit // notice the casing?
改成
this.credit = credit;
推荐阅读
- python - 特定格式的字典
- python - 类型错误:+= 不支持的操作数类型:“int”和“str”。我一直在尝试调试此错误 20 分钟
- mapbox - 有没有办法遍历图层的所有功能并更改特定功能的样式?
- javascript - 生成唯一值和过滤数据对象
- python - Python。将 for 循环中的值保留在列表中
- c# - 如何使用触摸使角色沿轴移动?
- python - 向 seaborn 条形图添加标签
- android - 导航组件取回片段结果返回起始目的地
- php - MYSQL SELECT 查询在 PHP 文件中不起作用
- memory - Varnish 6 LTS /w CentOS 8 不遵守内存限制?