gpt4 book ai didi

c# - 如何使 C# 构造函数语法更像 pythonic?

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:12 25 4
gpt4 key购买 nike

我对 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__的签名):

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 的初始化语法相似(如果不是完全相同)的构造函数语法?

最佳答案

这是使用 Named and Optional Arguments (C# Programming Guide) 完成的

Visual C# 2010 introduces named and optional arguments. Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.

关于c# - 如何使 C# 构造函数语法更像 pythonic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18321379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com