如何在C#中动态引用递增的属性?

Jef*_*urg 6 javascript c# reflection

我有称为reel1,reel2,reel3和reel4的属性.如何通过将整数(1-4)传递给我的方法来动态引用这些属性?

具体来说,我正在寻找如何在不知道对象名称的情况下获取对象引用.

在Javascript中,我会这样做:

temp = eval("reel" + tempInt);
Run Code Online (Sandbox Code Playgroud)

和temp将等于reel1,即对象.

似乎无法在C#中找出这个简单的概念.

Ree*_*sey 6

这通常是C#中避免的.通常有其他更好的选择.

话虽这么说,你可以使用Reflection来获取像这样的属性的值:

object temp = this.GetType().GetProperty("reel" + tempInt.ToString()).GetValue(this, null);
Run Code Online (Sandbox Code Playgroud)

但是,更好的选择可能是在您的班级上使用索引属性,这将允许您这样做this[tempInt].

  • 重申一下,不要这样做.使用索引器 (2认同)

Vla*_*lad 0

您可以使用包含属性名称的字符串来访问属性值PropertyInfo

例子:

PropertyInfo pinfo = this.GetType().GetProperty("reel" + i.ToString());
return (int)pinfo.GetValue(this, null);
Run Code Online (Sandbox Code Playgroud)