我在尝试创建程序时遇到问题。这个程序就像一张信用卡,问题是我放入“Credit”变量中的金额似乎根本不会影响变量,它保持为空。 以下是信用卡类:
我编辑了代码,因为我刚刚注意到我没有插入所有内容并且还包含了 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;
关于c# - 变量不持有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51008202/