简体   繁体   中英

Reflection to get and use class properties

I am trying to update a linked list from a datagridview using reflection so I don't have to write a line of code for each property.

The class:

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; }
}

One line of code per property works:

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

But there are many classes and class properties, so I'd prefer to use a loop and reflection, but I'm not sure how, and my attempt below has errors.

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.("
}

Thanks for any suggestions or links to further my understanding.

Reflection-based loop needs to use a different syntax:

  • Property type is a property of PropertyInfo ,
  • Convert has a ChangeType method that takes System.Type , and
  • Property assignment needs to be done by calling SetValue

Therefore, your loop would look like this:

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

I would suggest to use BindingSource . This way a changed value in the Grid will automatically be changed in your list:

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

dataGridView1.DataSource = bs;

This would solve the case where you want to update values manually changed in the grid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM