C# 如何使用相同的字符串名而不是变量名来使用变量的函数?

C# 如何使用相同的字符串名而不是变量名来使用变量的函数?,c#,unity3d,C#,Unity3d,我在一个反射问题中挣扎,实际上我不确定这是否是一个反射问题,但情况如下所示 public Image IMG1; int x = 1; string temp; temp = "IMG" + x.ToString(); //Now temp is a string with value "IMG1" 在Image类中,我们可以调用“sprite”属性。是否可以使用“临时精灵”而不是“IMG1.sprite” 改为 temp.sprite = newSprite; 非常感谢。我不确定您是否需要

我在一个反射问题中挣扎,实际上我不确定这是否是一个反射问题,但情况如下所示

public Image IMG1;
int x = 1;
string temp;
temp = "IMG" + x.ToString(); //Now temp is a string with value "IMG1"
在Image类中,我们可以调用“sprite”属性。是否可以使用“临时精灵”而不是“IMG1.sprite”

改为

temp.sprite = newSprite;

非常感谢。

我不确定您是否需要在您的案例中使用反射。 但我建议试着用字典。因此,在开始时,您需要将所有图像字段添加到字典:

Dictionary<string, Image> dict = new Dictionary<string, Image>();
dict.Add(nameof(IMG1), IMG1);
在性能方面,这种方法要好得多。 但是,如果您确实需要通过反射来实现,您可以查看“dynamic”关键字,如果您不熟悉反射,它可以简化反射的使用

或者通过使用常规反射,您可以尝试以下方法:

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

希望能有所帮助。

您需要创建一个包含
Sprite
属性的
MyClass
(对于temp),而不是使用字符串(对于temp)。然后,您可以重写
MyClass.ToString()
,按照您希望的方式组合字符串。然而,这是一个相对繁琐的方法;这对你的案子来说可能是过度设计的。如果你提供了一些你希望达到的总体目标的背景;我们可以给你一个更准确的答案,以避免过度杀戮。
temp
是字符串,没有
sprite
属性,所以没有。我想你应该解释一下你到底在做什么和为什么。这将帮助很多人回答你的问题。
dict[temp].sprite = xxxx
FieldInfo fieldInfo = typeof(YourClassWithImageField).GetField(temp);
Image img = fieldInfo.GetValue(ObjectWithYourField) as Image;
if (img != null)
{
    img.sprite = xxxx;
}