[英]Specify the default value for the parameterful property in C#
如何在 C# 中为参数属性指定默认值?
在探索 C# 时,我通过 C#书籍在CLR 中看到了以下摘录:
您可以为方法、构造函数方法和参数属性(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# 目前没有用于省略索引器值的有效语法。 p[]
根本就不是有效的 C#。
我不知道为什么 c# 团队允许定义一个不能使用的默认值,但这是一个只有他们才能回答的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.