簡體   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