c# - 反射获取和使用类属性

标签 c# class reflection gettype

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

但是有很多类和类属性,所以我更愿意使用循环和反射,但我不确定如何,并且我在下面的尝试有错误。

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

关于c# - 反射获取和使用类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848754/

相关文章:

C# 在 map 上显示 gps 位置

c# - AjaxControlToolkit ModelPopupExtender 显示屏幕左侧而不是中心

c++ - 在 C++ 中,如何在另一个嵌套类中使用嵌套类类型(两个嵌套类在同一个外部类下)

c# - 为什么 CanRead 和 CanWrite 在 C# 中为具有覆盖访问器的属性返回 false?

c# - C# 的 IVR 编程库

c++ - 类内类的访问方法

c++ - 为什么我在执行以下代码时出错?

c# - 使用 Autofac 解析通用接口(interface)

java - 泛型 - 获取引用类型

c# - .NET 类库作为带有 ServiceBusTopic 触发器的 Azure Function App 不起作用