c# - 变量不持有值

标签 c#

我在尝试创建程序时遇到问题。这个程序就像一张信用卡,问题是我放入“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/

相关文章:

c# - 如何让WebBrowser控件关闭jpg文件?

c# - 如何将现有项目推到列表末尾?

c# - RichTextBox的C#滚动

c# - 在 DirectX 中渲染环境

c# - 在草稿文件夹中保存一个项目也会创建一个空白的发件箱项目

c# - ReSharper 重新排序 String.Format() 参数

c# - 我应该使用回调还是引入公共(public)字段来帮助进行单元测试?

c# - 调用方法会降低性能吗?

C# List<int> 从 SQL 存储过程结果填充

c# - 如何使智能感知与 RazorEngine 一起工作?