2017-06-01 48 views
0

我在反射问题上挣扎,实际上我不确定它是否是反射问题,但情况如下所示。如何通过使用相同的字符串名称而不是变量名称来使用变量的功能?

public Image IMG1; 
int x = 1; 
string temp; 
temp = "IMG" + x.ToString(); //Now temp is a string with value "IMG1" 

在Image类中,我们有我们可以调用的“精灵”属性。是否有可能使用像“temp.sprite”而不是“IMG1.sprite”?

public Sprite newSprite; 
IMG1.sprite = newSprite; 

变化

temp.sprite = newSprite; 

非常感谢。

+1

而不是使用字符串(对于temp),您将不得不创建一个包含'Sprite'属性的'MyClass'(用于temp)。然后,您可以重写'MyClass.ToString()'来组合该字符串,因为它是您想要的。但是,这是一个相对繁琐的方法;这可能是完全过度的为您的情况。如果您提供了一些关于您希望整体实现的内容;我们可以给你一个更准确的答案,避免矫枉过正。 – Flater

+0

'temp'是字符串,没有'sprite'属性,所以** No **。我想你应该解释为什么,以及你在做什么。这将有助于很多人回答你的问题。 – Programmer

回答

1

我不确定您是否需要在您的案例中使用反射。 但我建议尝试去与词典。因此,在的游戏内需要添加你所有图片字段以词典:

Dictionary<string, Image> dict = new Dictionary<string, Image>(); 
dict.Add(nameof(IMG1), IMG1); 

那么你可以通过访问现场:

dict[temp].sprite = xxxx 

这种做法是当它涉及到性能更好。 但是,如果你真的需要反思,你可以看看'动态'关键字,如果你不熟悉它可以简化反射的使用。

或使用常规的反射你可以尝试这样的:

FieldInfo fieldInfo = typeof(YourClassWithImageField).GetField(temp); 
Image img = fieldInfo.GetValue(ObjectWithYourField) as Image; 
if (img != null) 
{ 
    img.sprite = xxxx; 
} 

希望它能帮助。