假設我們有下面的代碼。我想訪問具有索引器的類中 Main() 方法中的注釋突出顯示的元素。索引器在索引器代碼的“set”部分還有一個注釋,描述了要訪問元素的位置。如果我遺漏了什么,任何建議將不勝感激。
主要的():
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;
}
}
}
uj5u.com熱心網友回復:
在代碼中使用“value”關鍵字:
if(names.Contains(value))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342845.html
上一篇:用于登錄WpfC#的彩色文本
下一篇:如何在C#中進行單元測驗
