【问题标题】:Assigning a field value by passing its name通过传递名称来分配字段值
【发布时间】:2012-08-26 22:20:01
【问题描述】:

我一直在阅读其他示例,并且似乎可以通过传入字段的名称来分配字段的值。

private string fieldName;  //contains the name of the field I want to edit

void IObserver.Update(object data)
{       
    FieldInfo field = this.GetType().GetField(fieldName);

    if(field != null)
    {
        field.SetValue(this, data);         
    }   
}

字段总是以 null 结尾,我不知道为什么

【问题讨论】:

    标签: c# .net reflection field


    【解决方案1】:

    .Net 反射中的Get* 方法默认只搜索公共成员。
    要获取私有字段,请传递BindingFlags.NonPublic | BindingFlags.Instance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      相关资源
      最近更新 更多