如何从C#中的继承类传递值

时间:2018-09-23 20:25:51

标签: c# inheritance

由于某些原因,当我尝试从继承的类访问公共属性时,它返回0。这是我的代码。当我打印savings.AccountBalance时得到0。我在做什么错?我想使用继承类的属性或使用其变量。我不想公开变量,因此我将不得不将它们更改为protected而不是private

class AccountTest
{
    static void Main ( string[] args )
    {
        Account account = new Account ();    //declaring account object
        SavingsAccount savings = new SavingsAccount ();
        Console.Write ( "Enter account balance: " );
        account.AccountBalance = Convert.ToDecimal ( Console.ReadLine () );
        Console.WriteLine ( "Enter Interest rate in percentage: " );
        savings.Interest = Convert.ToInt32 ( Console.ReadLine () );
        Console.WriteLine ( $"Account Balance: {account.Balance}\nInterest rate: {savings.interest}\n" +
                           $"Savings Earned Interest: {savings.CalculateInterest()}" );
    }
}

第二堂课

class Account
{
    private decimal accountBalance;
    public Account () { }
    public Account ( decimal balance )
    {
        AccountBalance = balance;
    }
    public decimal AccountBalance
    {
        get
        {
            return accountBalance;
        }
        set
        {
            if (value < 0)
            {
                Console.WriteLine ( "Account balance cannot be negative number" );
            }
            else
            {
                accountBalance = value;
            }
        }
    }
    public decimal Balance
    {
        get
        {
            return accountBalance;
        }
    }
}

这是我的最后一堂课。为什么CalculateInterest方法返回0?

class SavingsAccount : Account
{
    public double interest;
    public SavingsAccount () : base () { }
    public SavingsAccount ( decimal initialBalance ) : base ( initialBalance )
    {
        initialBalance = AccountBalance;
    }
    public SavingsAccount ( double interests )
    {
        interests = Interest;
    }
    public double Interest
    {
        get
        {
            return interest;
        }
        set
        {
            if (value >= 0)
            {
                interest = value;
            }
            else
            {
                Console.WriteLine ( "Interest Cannot be Negative" );
            }
        }
    }
    public decimal CalculateInterest () => 
        Balance * Convert.ToDecimal ( interest / 100 );
}

这是我上一个问题的更新版本。

3 个答案:

答案 0 :(得分:3)

您有一些问题,因为缺少分号和属性不正确,所以代码无法编译,但是一旦完成,您的Person构造函数将不正确,因为您的分配方法错误。最后,getID属性没有被初始化,因此它将始终为0。

最后,由于您从Person继承了Id属性,因此getId属性是多余的,因此甚至不需要。如果要获取员工ID,请调用ID属性。

这是它的外观。

class Person 
{
    public Person (){}
    public Person (int ID)
    {
        Id = ID;
    }
    public int Id {get; set;} 
}

class Employee: Person
   {
        public Employee():base(){}
        public Employee(int emp):base(emp){}
    }

编辑:OP更新了此问题。

首先,我强烈建议您返回基础知识,并重新阅读构造函数的工作原理。在两个构造函数中的储蓄帐户类中,您都传入一个变量,但似乎无缘无故将其覆盖。我认为您误会了赋值运算符的工作方式。如果仅将参数传递给子类,则它将被正确分配,因为您调用了base()构造函数。

例如下面的构造函数有效,并将正确的余额分配给SavingsAccount实例

public SavingsAccount ( decimal initialBalance ) : base ( initialBalance ){}

此外,下面的构造函数没有任何意义,您先传递利息金额然后进行覆盖,因此始终为0。

public SavingsAccount ( double interests )
{
    interests = Interest;
}

代替在分配周围交换,以便属性以您在Interest = interests;中传递的正确值进行更新

如果您想进一步扩展此构造函数,还可以将它们混合使用,以使您的储蓄帐户既有利息又有余额,而不必使用如下属性:

public SavingsAccount ( decimal initialBalance, double interest ) : base ( initialBalance )
{
    Interest = interest;
}

第二,您误解了继承的工作原理,不需要子类和父类的实例。如果创建子类的实例,它将继承成员字段和方法。除非出于其他原因需要Account类的实例,否则不需要创建它。只需创建Saving实例就足够了,这将允许您访问Account类的方法/字段。例如下面的代码就足够了

SavingsAccount savings = new SavingsAccount (); //Creates SavingAccount instance
Console.Write ( "Enter account balance: " );
savings.AccountBalance = Convert.ToDecimal ( Console.ReadLine () ); //Assigns an account balance to SavingAccount instance you have created
Console.WriteLine ( "Enter Interest rate in percentage: " );
savings.Interest = Convert.ToInt32 ( Console.ReadLine () ); //Assigns an interst to SavingAccount instance you have created
Console.WriteLine ( savings.AccountBalance );

答案 1 :(得分:0)

您在getId类中声明了一个属性Employee,witch被初始化为默认值零。这就是empId也将被初始化为零的原因。您的id字段也不会被初始化和使用。如果您的意思是Id属性,则无需声明后备字段,因为它被声明为auto属性,所以witch将导致编译器生成后备字段beeing。

您的代码还有另一个问题。您的Person构造函数将参数ID的属性Id的值设置为零,并且可能不是您想要的。

因此,要清理代码,您可能需要使用类似的代码。

class Person 
{
    public Person (){}
    public Person (int id)
    {
        Id = id
    }

    public int Id {get;set} 
}

class Employee : Person
{
    private int empId;
    public Employee(): base(){}
    public Employee(int emp) : base(emp)
    {
        empId = Id;
    }
}

顺便说一句,如果empId的值与Id相同,则无需将Employee存储在单独的字段中。由于Person继承自upd(){},因此它也将具有该属性。

答案 2 :(得分:0)

我认为Person类的id和Employee类的empId应该是同一回事。如果是这样,那么Employee类中就不需要任何东西,因为Person类已经通过Id属性公开了ID。

如果您有构造函数Person(),则也不需要诸如Person(int ID)之类的构造函数,因为可以使用初始化通过Id属性分配id。而且在人员类中,我认为您实际上并不需要id和id,因为它们引用了两个不同的值。我认为您的意思是一样的吗?如果是这样,那么这里的代码将满足您的需求。

2000.00