gpt4 book ai didi

索引器的c#程序

转载 作者:行者123 更新时间:2023-11-30 18:07:56 25 4
gpt4 key购买 nike

这个程序有错误。谁能解决这个问题?

Error is :TempRecord already defines a member called 'this' with the same parameters value

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication6
{
class TempRecord
{
// Array of temperature values
private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F };
private int[] d= new int[10]{4,5,5,4,4,43,2,2,5,3};
// To enable client code to validate input
// when accessing your indexer.
//public int Length
//{
// get { return temps.Length; }
//}
// Indexer declaration.
// If index is out of range, the temps array will throw the exception.
public float this[int index]
{
get
{
return temps[index];
}

set
{
temps[index] = value;
}
}
public int this[int index]//error:TempRecord already defines a member called 'this' with the same parameters value
{
get
{
return d[index];
}

set
{
d[index] = value;
}
}
}

class Program
{
static void Main(string[] args)
{
TempRecord tempRecord = new TempRecord();
// Use the indexer's set accessor
tempRecord[3] = 58.3F;
tempRecord[5] = 60.1F;



// Use the indexer's get accessor
for (int i = 0; i < 10; i++)
{
System.Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]);
}
Console.WriteLine(tempRecord[2]);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

}
}
}

最佳答案

您有两个名为 this 的成员,它们采用相同的参数。这在 C#(或其他 .Net 语言,据我所知)中是不允许的。

如果两个成员都像您一样返回不同的类型,您会认为您能够做到这一点。但这会给编译器带来歧义。如果您有这样的代码,会调用哪个成员?

object x = tempRecord[3];

使一个或两个索引器成为一个方法。

关于索引器的c#程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3644765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com