[英]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. 我正在尝试使用反射从datagridview更新链接列表,因此我不必为每个属性编写一行代码。
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: 基于反射的循环需要使用不同的语法:
PropertyInfo
, PropertyInfo
, Convert
has a ChangeType
method that takes System.Type
, and Convert
有一个ChangeType
方法,它接受System.Type
和 SetValue
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
. 我建议使用
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. 这将解决您想要更新网格中手动更改的值的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.