C# 按字符串引用字段
这是一个非常简单的问题,但我无法通过25分钟的谷歌搜索找到一个好答案~ 我想引用存储在名为(string)的字段中的对象~ 差不多~C# 按字符串引用字段,c#,string,reflection,casting,reference,C#,String,Reflection,Casting,Reference,这是一个非常简单的问题,但我无法通过25分钟的谷歌搜索找到一个好答案~ 我想引用存储在名为(string)的字段中的对象~ 差不多~ private string ButtonName; public ActionPanel ActionPanel; private object reference; void main(){ ActionPanel = new ActionPanel(); reference = ActionPanel.ChangeSelectedAct
private string ButtonName;
public ActionPanel ActionPanel;
private object reference;
void main(){
ActionPanel = new ActionPanel();
reference = ActionPanel.ChangeSelectedActionBundle.(ButtonName);
}
我假设我将需要使用反射,但我不太确定这样做的正确方式:(反射将像这样工作(假设您尝试使用ButtonName的值名称获取“ChangeSelectedActionBundle”的属性):
我只是想说,我不同意“更好的语法”建议的编辑。@Burdock:如果你打算建议这样的编辑,你将有很多工作要做!(95%的答案使用
var
)。我已经回答了,谢谢你的帮助!!
Type type = ActionPanel.ChangeSelectedActionBundle.GetType();
PropertyInfo property = type.GetProperty(ButtonName);
object value = property.GetValue(ActionPanel.ChangeSelectedActionBundle, null);