【问题标题】:Reflection to get and use class properties反射以获取和使用类属性
【发布时间】:2017-06-10 11:10:53
【问题描述】:

我正在尝试使用反射从 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.("
}

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

【问题讨论】:

  • 您将列表绑定为DataSourceDataGridView 吗?
  • dgv数据源是来自linkedlist的bindinglist,linkedlist不直接绑定dgv

标签: c# class reflection gettype


【解决方案1】:

基于反射的循环需要使用不同的语法:

  • 属性类型是PropertyInfo的属性,
  • Convert 有一个采用 System.TypeChangeType 方法,并且
  • 需要通过调用SetValue来完成属性分配

因此,您的循环将如下所示:

foreach (var p in classProps) {
    p.SetValue(
        UdlyNode
    ,   Convert.ChangeType(
            GenericTable.Rows[IDX].Cells[p.Name].Value
        ,   p.PropertyType
        )
    );
}

【讨论】:

  • 感谢这真的帮助我更多地了解反射。抱歉 - 我只能接受一个答案,而 Mong 的答案更简单,但我赞成您的回复并将在其他地方使用代码。
【解决方案2】:

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

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

dataGridView1.DataSource = bs;

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

【讨论】:

  • 谢谢,它的工作原理 - 我不认为有这么简单的解决方案。
  • @Zeus 不客气。我都没有这样做,直到我绊倒了它。在此之前,我手动循环并搜索值。
猜你喜欢
  • 1970-01-01
  • 2018-06-05
  • 2011-02-15
  • 1970-01-01
  • 2020-12-27
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多