2013-11-27 100 views
1

我想通过名称在类实例中获取属性的值。我发现了很多解决方案,在网络上解决这样的方式问题:使用反射获取属性的值

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

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

但是编译器会通知我NullReferenceException在该行(第二个参数为空如果期望的属性不是不是的数组)。

请帮帮忙,

在此先感谢!

+1

我认为null是指未能检索到名称为“id”的财产。你的代码中该属性的外观如何? – Tigran

+0

请告诉我们什么类型是'userData'和它的结构。 –

回答

1

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

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

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

p.s.你确定“身份证”是一个财产,而不是一个领域?

+0

是的,你是对的,我的UserData.id是一个字段而不是属性。它用公共修饰符指定。我可以在不设置get和set方法的情况下从中检索值吗? –

+0

@ user3040712你大部分都是这样做的,但是使用'GetField(“id”)' –

+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

对于从CALSS获取属性格式值可以简单地访问如下,

userData.id;

相关问题