2009-08-08 4 views
1

난 그냥 반사를 시도하고있다 :왜 C# 리플렉션 코드가 충돌합니까?

using System; 
using System.Collections.Generic; 
using System.Reflection; 


public class CTest { 
    public string test; 
} 

public class MyClass 
{ 
    public static void Main() 
    { 
     CTest cTest = new CTest(); 
     Type t=cTest.GetType(); 
     PropertyInfo p = t.GetProperty("test"); 
     cTest.test = "hello"; 
     //instruction below makes crash 
     string test = (string)p.GetValue(cTest,null); 

     Console.WriteLine(cTest.GetType().FullName); 
     Console.ReadLine(); 
    } 
} 
+4

: 당신이 일반적으로 나쁜 생각 (클래스 외부에서) 필드를 감동 매우 특별한 일을하지 않는 한 '는'! = null'을 위해'GetProperty()'와 같은 호출에서 반환되었습니다. ** A-L-W-A-Y-S ** –

+0

자문을 구하십시오. CTest 변수의 이름을 cTest, _cTest, M_cTest 또는 여러분이 좋아하는 지역 변수의 명명 규칙으로 바꾸십시오. CTest.MyProp과 같은 줄이 정적 속성인지 또는 인스턴스 속성인지 여부를 확인하기가 어렵습니다. 버그가 찾기 힘들어집니다. – Dabblernl

+0

OK Ctest를 ctest로 변경했습니다. – programmernovice

답변

11

는 "test"는 필드의, 속성이 아닙니다. 이 멤버 변수입니다

CTest CTest = new CTest(); 
Type t = CTest.GetType(); 
FieldInfo p = t.GetField("test"); 
CTest.test = "hello"; 
string test = (string)p.GetValue(CTest); 

Console.WriteLine(CTest.GetType().FullName); 
Console.ReadLine();  
+0

감사합니다. FieldInfo에 대해 잘 모르 셨습니다. – programmernovice

4

테스트 속성되지 않습니다 : 당신은 FieldInfo가 얻을 Type.GetField 방법을 사용해야합니다.

using System; 
using System.Collections.Generic; 
using System.Reflection; 


public class CTest { 
    public string test; 
    public string test2 {get; set;} 
} 

public class MyClass 
{ 
    public static void Main() 
    { 
     CTest CTest = new CTest(); 
     Type t=CTest.GetType(); 
     FieldInfo fieldTest = t.GetField("test"); 
     CTest.test = "hello"; 
     string test = (string)fieldTest.GetValue(CTest); 
     Console.WriteLine(test); 


     PropertyInfo p = t.GetProperty("test2"); 
     CTest.test2 = "hello2"; 
     //instruction below makes crash 
     string test2 = (string)p.GetValue(CTest,null); 
     Console.WriteLine(test2); 

     Console.ReadLine();  
    } 
} 
+0

감사합니다. – programmernovice

8

다른 회원은 필드가 필드임을 관찰했습니다. 그러나 IMO는 가장 좋은 해결 방법은 입니다. ** 항상 ** ** 항상 ** ** 항상 ** 체크 값과 같은`P

public class CTest { 
    public string test { get; set; } 
} 
+0

나는 기본적으로 변수를 public으로 설정하고 가져오고 싶다고 생각했습니다. – programmernovice

+0

아니요; 당신이 get/set을 가지고 있다고 말하지 않는다면 공개 ** 필드 ** 일 것입니다. –

관련 문제