mercredi 25 janvier 2017

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.





Aucun commentaire:

Enregistrer un commentaire