2013-11-27 6 views
1

클래스 인스턴스에서 이름으로 속성 값을 가져 오려고합니다.리플렉션을 사용하여 속성 값 가져 오기

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

또는

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

하지만 컴파일러가 그 라인에서 나에게 NullReferenceException 통지 (두 번째 매개 변수는 NULL이어야합니다 :이 같은 방법으로 문제를 해결하기 위해 그물에 솔루션을 많이 발견 원하는 속성이 아닌 배열이 아닌 경우).

도와주세요,

미리 감사드립니다.

+1

null은 name "id"로 속성을 검색하지 못했음을 의미한다고 생각합니다. 코드에서 해당 속성은 어떤 모습입니까? – Tigran

+0

어떤 타입이'userData'인지와 그것의 구조를 보여주십시오. –

답변

1

userData에 "id"속성이 없으면 접근 방식이 실패합니다. 다음과 같이 시도하십시오 :

이렇게하면 절대로 Null 속성의 값을 가져올 수 없습니다.

p.s. "id"는 부동산이 아닌 필드입니까?

+0

예, 맞습니다. UserData.id는 속성이 아닌 필드입니다. public 한정자로 지정됩니다. get 및 set 메서드를 설정하지 않고 값을 검색 할 수 있습니까? –

+0

@ user3040712 당신은 대부분 같은 일을하지만'GetField ("id")' –

+0

으로 작동합니다. 큰. 고맙습니다! –

2

귀하의 Id 속성에 private 또는 protected 수정자가 있다고 생각합니다. 당신이 public 속성이있는 경우 새 dynamic 키워드를 사용할 수 있습니다

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; } 
    } 
} 

:

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

Id2, Id4 and Id5 즉, dynamic 작동하지 않습니다 그럼 당신은 GetProperty 방법의 첫 번째 오버로드를 사용해야합니다 키워드는 공용 프로세서가 없기 때문에 간단하게 아래에 액세스 할 수 있습니다 CALSS에서 때에 프로퍼티 값을 얻기 위해

관련 문제