我在 python 初始化程序(本质上是 Python 对象构造函数语法)方面有一些背景,在 Python 中实例化对象的语法如下:
class Account:
def __init__(self,name=None,address="Not Supplied",balance=0.0):
this.name = name
this.address=address
this.balance=balance
为什么呢,在 C# 中,我必须在构造函数方法的主体中提供默认值,而在 python 中我可以将它们声明为可选,并传入默认值(参见__init__
's 签名):
public class Account
{
private string name;
private string address;
private decimal balance;
public Account (string inName, string inAddress, decimal inBalance)
{
name = inName;
address = inAddress;
balance = inBalance;
}
public Account (string inName, string inAddress)
{
name = inName;
address = inAddress;
balance = 0;
}
public Account (string inName)
{
name = inName;
address = "Not Supplied";
balance = 0;
}
}
为什么我不能在 C# 中执行以下操作?
public class Account
{
private string name;
private string address;
private decimal balance;
public Account (string inName, string inAddress="not supplied", decimal inBalance=0;)
{
name = inName;
address = inAddress;
balance = inBalance;
}
是否可以在 C# 中使用与 Python 的初始化程序语法类似(如果不是完全重复)的构造函数语法?