如何从另一个 class 中的索引器访问 Main() 方法中的元素?

How to access element that is in the Main() method from an indexer that is in another class?

假设我们有下面的代码。我想访问具有索引器的 class 中的 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;
            }
        }
}

在您的代码中使用“值”关键字:

if(names.Contains(value))