获取和使用类属性的反射

时间:2017-01-25 10:10:08

标签: c# class reflection gettype

我正在尝试使用反射从datagridview更新链接列表,因此我不必为每个属性编写一行代码。

班级:

public class clsUnderlying
{
    public int UnderlyingID { get; set; }
    public string Symbol { get; set; }
    public double RiskFreeRate { get; set; }
    public double DividendYield { get; set; }
    public DateTime? Expiry { get; set; }
}

每个属性的一行代码有效:

UdlyNode.Symbol = (string)GenericTable.Rows[IDX].Cells["Symbol"].Value;
UdlyNode.Expiry = (DateTime)GenericTable.Rows[IDX].Cells["Expiry"].Value;
etc.

但是有很多类和类属性,所以我更喜欢使用循环和反射,但我不确定如何,并且下面的尝试有错误。

PropertyInfo[] classProps = typeof(GlobalVars.clsUnderlying).GetProperties(); 
foreach (var Prop in classProps)
{
    Type T = GetType(Prop); // no overload for method GetType
    UdlyNode.Prop.Name = Convert.T(GenericTable.Rows[IDX].Cells[Prop.Name].Value); // error on "Prop.Name" and "T.("
}

感谢您提供进一步理解的任何建议或链接。

2 个答案:

答案 0 :(得分:2)

基于反射的循环需要使用不同的语法:

  • 属性类型是PropertyInfo
  • 的属性
  • Convert有一个ChangeType方法,需要System.Type
  • 需要通过调用SetValue
  • 来完成属性分配

因此,你的循环看起来像这样:

foreach (var p in classProps) {
    p.SetValue(
        UdlyNode
    ,   Convert.ChangeType(
            GenericTable.Rows[IDX].Cells[p.Name].Value
        ,   p.PropertyType
        )
    );
}

答案 1 :(得分:1)

我建议使用BindingSource。这样,网格中的更改值将自动在列表中更改:

BindingSource bs = new BindingSource();
bs.DataSource = yourList;

dataGridView1.DataSource = bs;

这将解决您想要更新网格中手动更改的值的情况。

相关问题