繁体   English   中英

C#如何在运行时获取通用类的属性值

[英]C# How to get properties value of generic class at runtime

如何在运行时获取“ strx”的值和类型? 使用泛型时,无法在运行时获取单元格(属性)的值(由于底层代码为“ null”)。

   public class Foo 
    {
        public int x, y;
        public string strx, stry;
    }

    public void GetCellValueByName<T>(GridView gridview, string name/)
    {
        T = (T)Activator.CreateInstance(typeof(T));

        object row = gridview.GetRow(gridview.GetSelectedRows()[0]);

        if (row != null && row is T) 
        {
            columnType = (T)gridview.GetRow(gridview.GetSelectedRows()[0]);
            PropertyInfo info = columnType.GetType().GetProperty(name);
            if (info != null) 
            {  // Here I got always null
                info.GetValue(columnType, null);
            }
        }
    }

string valueOfStrx = GetCellValueByName<Foo>(grid, "strx");

问题是在类Foostrx是一个字段(成员变量):

public string strx, stry;

在您的方法中,尝试使用GetProperty ,但是找不到该字段:

PropertyInfo info = columnType.GetType().GetProperty(name);

因此,要么将成员更改为属性

public string strx { get; set; }
public string stry { get; set; }

或改用GetField

FieldInfo info = columnType.GetType().GetField(name);
// ...
info.GetValue(columnType); // Note that GetValue for a field does not take a second parameter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM