【问题标题】:How to change variable names in runtime如何在运行时更改变量名
【发布时间】:2021-12-20 21:07:15
【问题描述】:

我有一个循环,我需要动态创建Entries,然后,我需要在特定的Entry 上创建setFocus(),然后再创建另一个,等等。

如何在运行时更改变量的名称以识别它?

for(i = 0; i < list.Count; i++)
{
  //the result that I want:
  Entry entry + i = new Entry(){ Placeholder = "Entry number" + i.ToString() };
}

//result
entry1 =  /* Placeholder */ "Entry number 1";
entry2 =  /* Placeholder */ "Entry number 2";
entry3 =  /* Placeholder */ "Entry number 3";

编辑:

我忘了放一个我需要使用的 Entry 事件:

entries[i].Completed += (s, e) =>
{
   if (!entries[i].Text.Contains("\u00b2"))
   {
    entries[i].Text += "\u00b2";
   }
};
   entries[i].Focus();

当它进入这个事件时,它不知道我在调用什么条目,总是得到这个数组的最后一个条目。

【问题讨论】:

    标签: c# loops xamarin


    【解决方案1】:

    事件参数中的ssender - 即触发事件的对象

    entries[i].Completed += (s, e) =>
    {
       var entry = (Entry)s;
    
       if (!entry.Text.Contains("\u00b2"))
       {
         entry.Text += "\u00b2";
       }
    };
    

    【讨论】:

      【解决方案2】:

      你会使用某种集合,例如一个数组:

      var entries = new Entry[3];
      for(i = 0; i < list.Count; i++)
      {
        //the result that I want:
        entries[i] = new Entry(){ Placeholder = "Entry number" + i.ToString() };
      }
      
      //result
      entries[0] =  /* Placeholder */ "Entry number 1";
      entries[1] =  /* Placeholder */ "Entry number 2";
      entries[2] =  /* Placeholder */ "Entry number 3";
      

      要知道被调用的条目,您可以像 Jason 建议的那样转换 sender 参数,var entry = (Entry)s。或者捕获一个变量:

      // for loops require copying of the index to a local variable when capturing. 
      var currentIndex = i; 
      entries[i].Completed += (s, e) =>
      {
         if (!entries[currentIndex].Text.Contains("\u00b2"))
         {
          entries[currentIndex].Text += "\u00b2";
         }
      };
      

      变量名大多在编译之前就已经存在,所以询问如何在运行时更改它是一个无意义的问题。

      【讨论】:

      • 我更新了我的问题,我忘了写几行我正在努力做的事情。你能编辑你的答案并包括我现在问的吗?
      • 好的,可以了!谢谢。
      【解决方案3】:

      当你这样做时

      for (int i = 0; i < list.Count; i++)
      {
          entries[i].Completed += (s, e) =>
          {
             if (!entries[i].Text.Contains("\u00b2"))
             {
                entries[i].Text += "\u00b2";
             }
          };
      }
      

      你“capture”那个事件处理程序中的i变量,而不是它的。这意味着当 Completed 事件最终触发时,它使用最新的已知值“i”。

      解决方案是将值复制到一个新变量,在循环内声明:

      for (int i = 0; i < list.Count; i++)
      {
          int j = i;
          entries[j].Completed += (s, e) =>
          {
             if (!entries[j].Text.Contains("\u00b2"))
             {
                entries[j].Text += "\u00b2";
             }
          };
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-23
        • 2020-05-15
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        • 1970-01-01
        • 2013-05-30
        相关资源
        最近更新 更多