【发布时间】:2021-10-31 07:56:38
【问题描述】:
假设我们有下面的代码。我想访问具有索引器的类的 Main() 方法中的注释突出显示的元素。 索引器还在索引器代码的“set”部分中有一个注释,描述了要访问元素的位置。如果我遗漏了什么,任何建议都会非常感激。
Main():
arrayaccess aa = new arrayaccess();
string a = "karl";
if (a is string)
Console.WriteLine(aa[a]);
else
{
double d = Convert.ToDouble(a);
d = Math.Floor(d);
Console.WriteLine(aa[Convert.ToByte(d)]);
}
//set code
aa[3] = "karl";//the name (string) karl is to be accessed in the indexer of "ArrayClass" class.
class arrayaccess
{
private string[] names = new string[] { "carl", "karl", "doe", "john" };
public string this[object index]
{
get
{
if (index is string)
{
if (names.Contains(index))
return "found";
else return "not found";
}
else
{
if (Convert.ToByte(index) >= names.Length)
throw new IndexOutOfRangeException("Index should be less than or equal to 3");
return names[Convert.ToByte(index)];
}
}
set
{
//it's easy to do with the get accessor
if (names.Contains(/*value here*/))//want to access here
throw new ArgumentException("Sorry, duplicate" +
"values not allowed");
else names[Convert.ToByte(index)] = value;
}
}
}
【问题讨论】:
-
有什么问题?你有错误吗?有什么不工作吗?
-
如果问题与访问
set访问器中的传入值有关,是否有某些原因不能直接说if (names.Contains(value))? -
没有错误,我只想检查通过 aa[0]="karl" 传递的名称(“karl”)是否将被索引器的 set{} 使用在“名称”中" arrayaccess 类的数组。
-
那你在问什么?你想要什么反馈?
-
顺便说一句,由于您的后备存储是一个数组,并且数组是固定长度的,您可能需要在您的
set方法中检查index是否超出范围。跨度>