2009-08-08 16 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は、」それは、フィールドのプロパティではありません。あなたはFieldInfoを取得するためにType.GetFieldメソッドを使用する必要があります。

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

テストは、それがメンバ変数で、プロパティではありません。

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を持っていると言っていない限り、それはpublic **フィールド**の場合です。 –

関連する問題