使用反射获取属性的值

时间:2013-11-27 07:58:47

标签: c# reflection

我试图在类实例中按名称获取属性的值。我在网上找到了很多解决方案,以这样的方式解决问题:

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

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

但编译器在该行中通知我NullReferenceException(如果所需的属性不是不是的数组,则第二个参数应为null。)

请帮忙,

提前谢谢!

3 个答案:

答案 0 :(得分:2)

我认为您的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关键字,因为它们没有公开访问者。

答案 1 :(得分:1)

如果userData没有“id”属性,您的方法将失败。试试这个:

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

这样你就永远不会检索Null属性的值。

P.S。你确定“id”是属性而不是字段吗?

答案 2 :(得分:-1)

从类中获取属性值只需访问如下,

userData.id;