C# .Net 4.0 命名参数和默认参数

标签 c# c#-4.0

您认为命名参数和默认参数将在 C#.Net 4.0 中增加什么值(value)?

这些有什么好的用途(尚未通过重载和覆盖实现)?

最佳答案

它可以使构造函数更简单,尤其是对于不可变类型(这对线程很重要)- see here for a full discussion .可能没有应该的好,但比有很多重载要好。您显然不能对不可变对象(immutable对象)使用对象初始值设定项,因此通常:

new Foo {Id = 25, Name = "Fred"}

不可用;我会满足于:

new Foo (Id: 25, Name: "Fred")

这可以扩展到简化重载的一般想法,但在大多数情况下,我更喜欢宣传合法组合的重载。 IMO,构造函数有点不同,因为您只是(通常)定义初始状态。

COM 方面的事情对很多人来说也很重要,但我只是没有使用太多 COM 互操作 - 所以这对我来说不是重要的。


编辑评论;他们为什么不使用与属性相同的语法呢?简单 - 它可能与其他成员/变量不明确(这不是属性的问题);举个例子:

[XmlElement("foo", Namespace = "bar")]

它使用一个常规参数(给构造函数“foo”)和一个命名赋值。因此,假设我们将其用于常规命名参数:

SomeMethod("foo", SecondArg = "bar");

(也可以是一个构造函数;为了简单起见,我使用了一个方法)

现在...如果我们有一个名为 SecondArg 的变量或属性怎么办?这在使用 SecondArg 作为 SomeMethod 的命名参数和将“bar”分配给 SecondArg 并传递“bar”之间会产生歧义"作为常规参数

为了说明,这在 C# 3.0 中是合法的:

    static void SomeMethod(string x, string y) { }
    static void Main()
    {
        string SecondArg;
        SomeMethod("foo", SecondArg = "bar");
    }

显然,SecondArg 可以是属性、字段、变量等...

替代语法没有这种歧义。


编辑 - 280Z28 的这一部分:很抱歉在这里添加这个,但这并不是一个真正独特的答案,而且它对于评论和包含代码来说太长了。您暗示了歧义,但您的示例并未突出决定性案例。我认为您提供的示例指出了一些可能令人困惑的地方,但围绕对象初始值设定项所需的 {} 可防止潜在的语法歧义。我对以下代码的解释嵌入为多行 block 注释。

[AttributeUsage(AttributeTargets.Class)]
public sealed class SomeAttribute : Attribute
{
    public SomeAttribute() { }

    public SomeAttribute(int SomeVariable)
    {
        this.SomeVariable = SomeVariable;
    }

    public int SomeVariable
    {
        get;
        set;
    }
}

/* Here's the true ambiguity: When you add an attribute, and only in this case
 * there would be no way without a new syntax to use named arguments with attributes.
 * This is a particular problem because attributes are a prime candidate for
 * constructor simplification for immutable data types.
 */

// This calls the constructor with 1 arg
[Some(SomeVariable: 3)]
// This calls the constructor with 0 args, followed by setting a property
[Some(SomeVariable = 3)]
public class SomeClass
{
}

关于C# .Net 4.0 命名参数和默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/686322/

相关文章:

c# - 如何使用动态 settings.Blah 而不是 AppSettings ["blah"]?

c# - 如何在 PowerPoint 中以编程方式更改幻灯片布局?

c# - 将固定长度文件中的数据读入类对象

linq - Entity Framework Extended - 简单删除给我空引用

c# - 我可以通过编程方式确定接口(interface)要求/依赖关系/继承吗?

c# - 使用 log4net + AutoFac 拦截器记录所有处理的异常

c# - 了解委托(delegate)和任务

c# - 在 linq 查询中设置动态排序名称字段

c# - 为什么我无法访问我的专栏?

C# 字符/字节编码相等