【问题标题】:using reflection to set member's value使用反射设置成员的值
【发布时间】:2014-08-25 06:33:05
【问题描述】:

我有一个DataGridView 有很多行,每行包含两个单元格, 当cell[0]= namecell[1]= value 对应于类中的成员时(也具有完全相同的名称)

我想使用反射来使用DataGridView 设置该类的属性 像这样 : 使用来自c# - How to iterate through classes fields and set properties的问题

GlobalParam.Params2 ParseDataGridForClass(System.Windows.Forms.DataGridView DataGrid)
{
    GlobalParam.Params2 NewSettings2 = new GlobalParam.Params2();
    foreach (System.Windows.Forms.DataGridViewRow item in DataGrid.Rows)
    {
        if (item.Cells[0].Value != null && item.Cells[1].Value != null)
        {
            Type T = NewSettings2.GetType();
            PropertyInfo info = T.GetProperty(item.Cells[0].Value.ToString());

                if (!info.CanWrite)
                continue;
            info.SetValue(NewSettings2,  
            item.Cells[1].Value.ToString(),null);
        }

    }
    return NewSettings2;
}

NewSettings 的样子

struct NewSettings 
{
    string a { get; set; }
    string b { get; set; }
    string c { get; set; }
}

在迭代时,我看到没有任何属性被改变 意味着 NewSettings 在它的所有属性中都保持为空

可能是什么问题?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    首先,您提供的结构上的属性是私有的,因此您的结构上的 GetProperty 应该返回 null,因为它将无法获取私有属性。其次,结构是值类型,而类是引用类型。这意味着您需要将正在使用的结构装箱到引用类型中,以保留其值。有关信息,请参阅随附的工作示例。属性 a 被公开,结构被装箱。

    struct NewSettings
    {
        public string a { get; set; }
        string b { get; set; }
        string c { get; set; }
    }
    

    这就是设置属性的方式。

    NewSettings ns = new NewSettings();
    var obj = (object)ns;
    PropertyInfo pi = ns.GetType().GetProperty("a");
    
    pi.SetValue(obj, "123");
    
    ns = (NewSettings)obj;
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2020-05-18
      相关资源
      最近更新 更多