【问题标题】:How to access element that is in the Main() method from an indexer that is in another class?如何从另一个类中的索引器访问 Main() 方法中的元素?
【发布时间】: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 是否超出范围。跨度>

标签: c# .net class indexer


【解决方案1】:

在代码中使用“value”关键字:

if(names.Contains(value))

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2013-03-20
    相关资源
    最近更新 更多