c# - 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;
}
}
解决方案
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
.
推荐阅读
- android - Android Studio 在升级 react 原生版本后总是生成超过 80 mb 的 apk
- magento-1.9 - Magento 1.9.4 管理员停止工作,得到“无效的表单密钥。请刷新页面。” 每时每刻
- java - 验证 bean 在 Java 11 和 spring boot 2.5.3 中不起作用
- iis - IIS 实时更新
- google-cloud-platform - 我想知道 Google Home 帐户链接详细步骤(使用 OAuth)
- python - tensorflow - 导入错误:无法导入名称 rnn_cell_impl
- python - 如何在 Linux 上使用 pytest 启用 python 选择器?
- javascript - 如何根据 uipath 表单中的表单加载条件禁用字段?
- javascript - React 原生 firebase+webrtc 进行视频通话
- python - 从验证码中删除曲线/线条(不阻止 ocr)