![](/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.