C# 2.0-3.0 是否支持方法的命名参数?

发布于 2024-08-11 02:58:26 字数 167 浏览 5 评论 0原文

有没有办法像 Perl/Python 中那样使用命名参数,

例如

object.method(arg1 => value1, arg2 => value2, arg3 => 0);

在 C# 4.0 之前的 C# 中?

Is there a way to have named arguments like in perl/python

for example

object.method(arg1 => value1, arg2 => value2, arg3 => 0);

in C# prior to C# 4.0?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

埋情葬爱 2024-08-18 02:58:26

方法命名参数是 C# 4.0 功能。 (C# < 4.0 中不能有方法可选参数)

method named arguments are C# 4.0 feature. (You can't have method optional parameters in C# < 4.0)

世俗缘 2024-08-18 02:58:26

在C# 4.0之前这是不可能的。

顺便说一句,不存在 C# 2.5 这样的东西。

It is not possible before C# 4.0.

BTW, there is no such thing as C# 2.5.

染柒℉ 2024-08-18 02:58:26

虽然与命名参数不完全匹配,但 C# 3.0 中的构造函数有一些类似的内容,称为“对象初始值设定项",让您在使用 new 运算符时定义公共属性的值。这可以让你做这样的事情:

Person p = new Person()
{
    FirstName = "John",
    LastName = "Doe",
    Address = new Address()
    {
        Street = "1234 St.",
        City = "Phoenix"
    }
};

现在为了利用它,你必须调用 new 运算符(因此它不适用于方法)并且你设置的属性需要具有相同的访问权限他们必须允许您这样做:

Person p = new Person();

p.FirstName = "John";
p.LastName = "Doe";

Address a = new Address();
a.Street = "1234 St.";
a.City = "Phoenix";

p.Address = a;

因此,这不会让您绕过 public get 但可以绕过 protected set 属性(您不能仅通过以下方式初始化属性)这个方法)。这可以使您的代码更具可读性,尽管程度不如命名参数。

While not an exact match for named arguments, there is something in C# 3.0 for constructors that is similar called "object initializers" that let you define values for public properties when you use the new operator. This lets you do stuff like this:

Person p = new Person()
{
    FirstName = "John",
    LastName = "Doe",
    Address = new Address()
    {
        Street = "1234 St.",
        City = "Phoenix"
    }
};

Now in order to utilize this you have invoke the new operator (so it won't work for methods) and the properties that you are setting need to have the same access that they would have to allow you to do this:

Person p = new Person();

p.FirstName = "John";
p.LastName = "Doe";

Address a = new Address();
a.Street = "1234 St.";
a.City = "Phoenix";

p.Address = a;

So this won't let you circumvent public get but protected set properties (you can't make a property only initialized via this method). This can make your code more readable, though not to the degree that named arguments can.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文