我有一个简短的问题。我有一个类Bank
,它需要具有不同数量的构造函数的属性。
class Program
{
static void Main(string[] args)
{
Bank ing = new Bank("ing");
int AccountNrName1 = ing.OpenAccount("Name", "LastName", "HouseNumber", "PostalCode");
int AccountNrName2 = ing.OpenAccount("Name", "LastName", "HouseNumber", "PostalCode", Balance, Minimum);
}
构造函数 "OpenAccount" 必须返回这两种情况(AccountNrName1, AccountNrName2(。这是我到目前为止所拥有的:
public class Bank
{
private string name, lastname, housenumber, postalcode;
private int openaccount;
private int balance;
private int min;
public int OpenAccount(string Name, string LastName, string HouseNumber, string PostalCode, int Balance, int Min)
{
name = Name;
lastname = LastName;
housenumber = HouseNumber;
postalcode = PostalCode;
balance = Balance;
min = Min;
return openaccount;
}
}
方法可以有可选参数,但是,你也可以重载 - 所以,虽然你似乎想要一个构造函数(因为你正在创建对象,但是,你可以让它成为方法......但你确实需要先制作对象!(:
您可能有 2 个构造函数来允许这些条件:
public OpenAccount (String name, String LastName, String Housenumber, String Postcode)
{ do stuff }
public OpenAccount (String name, String LastName, String Housenumber, String Postcode, int balance, int min)
{ do stuff }
或者你可以做
public OpenAccount (String name, String LastName, String Housenumber, String Postcode, int balance=0, int min=0)
{do stuff}
这允许您自动设置这些值(如果未提供(。我没有检查它是否适用于构造函数,但它应该。
您需要一个类来保存帐户信息。
public class Account {
public Account(int accountNumber) { AccountNumber = accountNumber; }
public int AccountNumber { get; private set; }
public string Name { get;set; }
public string LastName { get;set; }
public string HouseNumber { get;set; }
public string PostalCode { get;set; }
public int Balance { get;set; }
public int Min { get;set; }
}
Bank
将持有一系列账户,并允许您开设账户
public class Bank {
string name;
int accountIds = 0;
List<Account> accounts = new List<Account>();
public Bank(string bankName) {
name = bankName;
}
//Open an account and return the account number
//Using optional parameters to allow
//OpenAccount("Name", "LastName", "HouseNumber", "PostalCode");
//OpenAccount("Name", "LastName", "HouseNumber", "PostalCode", Balance, Minimum);
public Account OpenAccount(string Name, string LastName, string HouseNumber, string PostalCode, int Balance = 0, int Min = 0) {
var newAccount = new Account(++accountIds) {
Name = Name;
LastName = LastName;
HouseNumber = HouseNumber;
PostalCode = PostalCode;
Balance = Balance;
Min = Min;
};
accounts.Add(newAccount);
return newAccount;
}
}
所以现在当你打电话给银行开户
class Program {
static void Main(string[] args) {
Bank ing = new Bank("ing");
Account AccountNrName1 = ing.OpenAccount("Name", "LastName", "HouseNumber", "PostalCode");
Account AccountNrName2 = ing.OpenAccount("Name", "LastName", "HouseNumber", "PostalCode", Balance, Minimum);
}
}
您应该取回已打开的帐户,并填充所有属性。