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

Specify the default value for the parameterful property in C#

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

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

You can specify default values for the parameters of methods, constructor methods, and parameterful properties (C# indexers). You can also specify default values for parameters that are part of a delegate definition. Then, when invoking a variable of this delegate type, you can omit the arguments and accept the default values.

因此,该摘录让我尝试了以下代码:

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[]?我在这里错过了什么?

如警告所述:

...that is used in contexts that do not allow optional arguments...

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

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