获取和使用 class 属性的反射

Reflection to get and use class properties

我正在尝试使用反射更新来自 datagridview 的链接列表,因此我不必为每个 属性.

编写一行代码

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

每行代码 属性 有效:

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

但是有很多 classes 和 class 属性,所以我更喜欢使用循环和反射,但我不确定如何,我下面的尝试有错误。

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

感谢您提供任何建议或链接以加深我的理解。

我建议使用 BindingSource。这样,网格中更改的值将自动在您的列表中更改:

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

dataGridView1.DataSource = bs;

这将解决您想要更新在网格中手动更改的值的情况。

Reflection-based 循环需要使用不同的语法:

  • 属性 类型是 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
        )
    );
}