2012-04-25 7 views
4

可能性の重複:3 properties
C# How can I get the value of a string property via Reflection?プロパティ名とその値を取得するには?

public class myClass 
{ 
    public int a { get; set; } 
    public int b { get; set; } 
    public int c { get; set; } 
} 


public void myMethod(myClass data) 
{ 
    Dictionary<string, string> myDict = new Dictionary<string, string>(); 
    Type t = data.GetType(); 
    foreach (PropertyInfo pi in t.GetProperties()) 
    { 
     myDict[pi.Name] = //...value appropiate sended data. 
    } 
} 

単純なクラス。私はこのクラスのオブジェクトを送ります。 どうすればいいですか?すべてproperty namesとその値を取得できます。 〜へdictionary

+0

私はこの質問が何度も答えられたのを見ました:(http://stackoverflow.com/questions/987982/c-sharp-how-can-i-get-the-value-of-a-string- property-via-reflection – daryal

+0

@daryal次に、質問を重複してリンクして閉じるよう投票しますか? –

+1

btw、ネットではいくつかの命名規則があります –

答えて

16
foreach (PropertyInfo pi in t.GetProperties()) 
    { 
     myDict[pi.Name] = pi.GetValue(data,null).ToString(); 

    } 
+1

シンプルで偉大な、thanx – Saint

+1

downvoteの理由はありますか? –

+0

@AdrianIftode、それは私たちすべてが1つを持っているように見える(OPを含む)。私はあなたに票を投じて報いた。 –

5

これは、あなたが必要なものを行う必要があります。

MyClass myClass = new MyClass(); 
Type myClassType = myClass.GetType(); 
PropertyInfo[] properties = myClassType.GetProperties(); 

foreach (PropertyInfo property in properties) 
{ 
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(myClass, null)); 
} 

出力:

名前:、値:0

名:B、値:0

名前:c、値:0

関連する問題