【问题标题】:Specify the default value for the parameterful property in C#在 C# 中指定参数属性的默认值
【发布时间】:2020-04-07 19:04:25
【问题描述】:

如何在 C# 中指定参数属性的默认值?

在探索 C# 时,我在 CLR via C# 一书中看到以下摘录:

您可以为方法、构造方法的参数指定默认值,以及 参数属性(C# 索引器)。您还可以为以下参数指定默认值 是委托定义的一部分。然后,在调用此委托类型的变量时,您可以 省略参数并接受默认值。

所以,这段摘录让我尝试了以下代码:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace myprogram
{
    class Program
    {
        int this[int index = 0] {
            get {
                return 7;
            }
            set {

            }
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p[]);
        }
    }
}

代码无法编译并产生以下错误:

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "msCompile",
    "code": "CS0443",
    "severity": 8,
    "message": "Syntax error; value expected [C:\\Projects\\dotNet\\Console.NET\\Console.NET.csproj]",
    "startLineNumber": 20,
    "startColumn": 33,
    "endLineNumber": 20,
    "endColumn": 33
}

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "csharp",
    "code": "CS0443",
    "severity": 8,
    "message": "Syntax error; value expected [Console.NET]",
    "source": "csharp",
    "startLineNumber": 20,
    "startColumn": 33,
    "endLineNumber": 20,
    "endColumn": 34
}

还会产生以下警告:

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "csharp",
    "code": "CS1066",
    "severity": 4,
    "message": "The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments [Console.NET]",
    "source": "csharp",
    "startLineNumber": 9,
    "startColumn": 22,
    "endLineNumber": 9,
    "endColumn": 27
}

那么,为什么我不能在调用中使用默认参数:p[]?我在这里错过了什么?

【问题讨论】:

    标签: c# properties default indexer default-parameters


    【解决方案1】:

    如警告所述:

    ...用于不允许可选参数的上下文...

    C# 目前没有用于省略索引器值的有效语法。 p[] 根本不是有效的 C#。

    我不知道为什么 c# 团队允许定义一个不能使用的默认值,但这是一个只有他们才能回答的问题。

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      相关资源
      最近更新 更多