首页 > 解决方案 > Class Object, Incorporating a separate class as a field

问题描述

I have two classes but I need to link CheckingAccount.cs in Customer.cs. The professor for my class mentioned Has A but I'm not entirely sure what he was referring to. Here is my class files. They need to have a constructor and I believe I have that part right. I need to have a checking account field w/in the Customer.cs class, but I'm not sure how to link them. Any help would be greatly appreciated.

Customer.CS

class Customer
{
    public string CustomerName { get; set; }
    //Need to have a field here with the Checking Account Object.

    public Customer(string _customerName)
    {
        CustomerName = _customerName;
    }
}

CheckingAccount.CS

class CheckingAccount
{
    public decimal AccountBalance {get; set;}
    public int AccountNumber { get; set; }

    public CheckingAccount(decimal _accountBalance, int _accountNumber)
    {
        AccountBalance = _accountBalance;
        AccountNumber = _accountNumber;
    }
}

标签: c#class

解决方案


This has nothing to do with files. It has to do with types and objects. Classes are types. Therefore, you must have a property of CheckingAccount type in class Customer and pass it a CheckingAccount object in the constructor:

class Customer
{
    public string CustomerName { get; set; }

    public CheckingAccount Account { get; set; }

    public Customer(string customerName, CheckingAccount account)
    {
        CustomerName = customerName;
        Account = account;
    }
}

Then you can create a customer like this:

var account = new CheckingAccount(100m, 123); // Create CheckingAccount object.
var customer = new Customer("xTwisteDx", account);

If the account doesn't change during the lifetime of the customer object, you can also make the property read-only.

public CheckingAccount Account { get; }

Such a property can only be initialized in the constructor or by using an initializer as in:

public CheckingAccount Account { get; } = new CheckingAccount(0m, 0);

The same is true for the CustomerName.


推荐阅读