![](/img/trans.png)
[英]How to use reflection to get properties of a base class before properties of the derived class
[英]Reflection to get and use class properties
我正在尝试使用反射从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.("
}
感谢您提供任何建议或链接以进一步了解我。
基于反射的循环需要使用不同的语法:
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
)
);
}
我建议使用BindingSource
。 这样,网格中的更改值将自动在列表中更改:
BindingSource bs = new BindingSource();
bs.DataSource = yourList;
dataGridView1.DataSource = bs;
这将解决您想要更新网格中手动更改的值的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.