首页 > 解决方案 > 变量不保存值

问题描述

我正在尝试创建的程序有问题。这个程序就像一张信用卡,问题是我放入“信用”变量的金额似乎根本不影响该变量,它保持为空。以下是信用卡类:

我已经编辑了代码,因为我刚刚注意到我没有插入所有内容并且还包含了 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();
        }
    }

}

标签: c#

解决方案


那是因为在您的构造函数中,您将属性分配回自身,而不是传递的值,即

this.credit = Credit // notice the casing?

改成

this.credit = credit;

推荐阅读