簡體   English   中英

使用反射獲取屬性的值

[英]Getting the value of the property using reflection

我正在嘗試通過類實例中的名稱來獲取屬性的值。 我在網上找到了很多解決方案,可以通過以下方式解決問題:

var value = (int)userData.GetType().GetProperty("id").GetValue(userData, null);

要么

var value = (int)GetType().GetProperty("id").GetValue(userData, null);

但編譯器會在該行中通知我NullReferenceException (如果所需屬性不是一個不是數組,則第二個參數應為null)。

請幫忙,

提前致謝!

我認為您的Id屬性具有privateprotected修飾符。 然后,您必須使用GetProperty方法的第一個重載:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Test t = new Test();
        Console.WriteLine(t.GetType().GetProperty("Id1").GetValue(t, null));
        Console.WriteLine(t.GetType().GetProperty("Id2").GetValue(t, null));
        Console.WriteLine(t.GetType().GetProperty("Id3").GetValue(t, null));

        //the next line will throw a NullReferenceExcption
        Console.WriteLine(t.GetType().GetProperty("Id4").GetValue(t, null));
        //this line will work
        Console.WriteLine(t.GetType().GetProperty("Id4",BindingFlags.Instance | BindingFlags.NonPublic).GetValue(t, null));


        //the next line will throw a NullReferenceException
        Console.WriteLine(t.GetType().GetProperty("Id5").GetValue(t, null));
         //this line will work
        Console.WriteLine(t.GetType().GetProperty("Id5", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(t, null));
    }

    public class Test
    {
        public Test()
        {
            Id1 = 1;
            Id2 = 2;
            Id3 = 3;
            Id4 = 4;
            Id5 = 5;
        }

        public int Id1 { get; set; }
        public int Id2 { private get; set; }
        public int Id3 { get; private set; }
        protected int Id4 { get; set; }
        private int Id5 { get; set; }
    }
}

如果您具有public屬性,則可以使用新的dynamic關鍵字:

static void Main()
{
    dynamic s = new Test();
    Console.WriteLine(s.Id1);
    Console.WriteLine(s.Id3);
}

請注意, Id2, Id4 and Id5不能與dynamic關鍵字一起使用,因為它們沒有公共的acessor。

如果userData沒有“ id”屬性,則您的方法將失敗。 試試這個:

var selectedProperty = from property in this.GetType().GetProperties()
                       where property.Name == "id" 
                       select property.GetValue(this, null);

這樣,您將永遠不會檢索Null屬性的值。

ps您確定“ id”是屬性而不是字段嗎?

要從calss獲取屬性值,只需訪問以下內容,

userData.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM