【问题标题】:Referencing a field by string通过字符串引用字段
【发布时间】:2013-09-30 09:59:14
【问题描述】:

一个很简单的问题,但是我25分钟google都找不到好的答案~

我想引用一个存储在名为(字符串)的字段中的对象~

有点像~

private string ButtonName;
public ActionPanel ActionPanel;
private object reference;

void main(){
     ActionPanel = new ActionPanel();
     reference = ActionPanel.ChangeSelectedActionBundle.(ButtonName);

    }

我假设我需要使用反射,但我不太确定这样做的正确方法:(

【问题讨论】:

    标签: c# string reflection casting reference


    【解决方案1】:

    反射会像这样工作(假设您尝试使用 ButtonName 值的名称获取“ChangeSelectedActionBundle”的属性):

    Type type = ActionPanel.ChangeSelectedActionBundle.GetType();
    PropertyInfo property = type.GetProperty(ButtonName);
    object value = property.GetValue(ActionPanel.ChangeSelectedActionBundle, null);
    

    【讨论】:

    • 我只想说我不同意“更好的语法”建议的编辑。 @Burdock:如果您打算提出这样的编辑建议,您将有很多工作要做! (95% 的答案使用var)。
    • 点了,谢谢你的帮助!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 2014-08-11
    • 2017-07-25
    相关资源
    最近更新 更多