【问题标题】:Mapping properties to array indexes将属性映射到数组索引
【发布时间】:2011-12-06 14:50:40
【问题描述】:

我在一个类中有几个这样的属性:

property1_1 {get;set;}
property1_2 {get;set;}
property1_3 {get;set;}
...
property9_1 {get;set;}
property9_2 {get;set;}
property9_3 {get;set;}

这些属性需要映射到数组中的索引,例如:

array[0].property1 = property1_1
array[0].property2 = property1_2
array[0].property3 = property1_3
...
array[8].property1 = property9_1
array[8].property2 = property9_2
array[8].property3 = property9_3

大约有一百个这样的属性需要像这样映射,我宁愿不必通过索引单独分配它们。我已经研究过使用反射和其他一些想法,但没有一个真的“感觉”更好。

有什么想法吗?

谢谢。

【问题讨论】:

  • 我相信你最好的选择是反射,你没有选择反射有什么特别的原因吗?我想您可以编写一个快速脚本来自动生成所有作业,但我想这不是重点...
  • 我不确定为什么“感觉”对于反射解决方案非常重要。这是最简单、最直接的路线。
  • 你到底是什么意思?因为您可以在结构或类中组合三个属性。如果您将生成一个数组,其中的元素属于这种类型。还是我看错了?
  • 反思可能是我最终重构它的方式。虽然我并不太关心性能,但我的想法是必须反映所有这些属性,这似乎不像通过索引直接分配它们那样有效。减少代码行数?是的。表现更好?不确定。
  • 抱歉,我花了这么长时间才回到这里。我已经继续并实施了反射来解决这个问题。最后一个原因只是为了消除代码的优势。可衡量的性能根本没有受到影响。老实说,我应该从一开始就这样做。

标签: c# arrays class properties


【解决方案1】:

你能不能试试这样的..?

公共结构位置结构 { 公共字符串位置; 公共 int 坐标X; 公共 int 坐标; 公共 int 坐标Z; }

public class Map
{
   positionStruct [] positionArray = new positionStruct[100];


   public positionStruct this[int index] 
   {
      get { return positionArray[index]; }
      set { positionArray[index] = value; }
   } 
}

//That way you can access the array with Map[index]. Hope this helps

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多