2015-04-01 192 views
-3

我有一個類Class1獲取領域

public class Class1 
{ 
    public string ABC { get; set; } 
    public string DEF { get; set; } 
    public string GHI { get; set; } 
    public string JLK { get; set; } 
} 

我怎樣才能得到的名單,在這種情況下,「ABC」,「DEF」,... 我想獲取所有公共領域的名稱。

我試過如下:

Dictionary<string, string> props = new Dictionary<string, string>(); 

foreach (var prop in classType.GetType().GetProperties().Where(x => x.CanWrite == true).ToList()) 
{ 
    //Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(classitem, null)); 
    //objectItem.SetValue("ABC", "Test"); 
    props.Add(prop.Name, ""); 
} 

和:

var bindingFlags = BindingFlags.Instance | 
BindingFlags.NonPublic | 
BindingFlags.Public; 
var fieldValues = classType.GetType() 
          .GetFields(bindingFlags) 
          .Select(field => field.GetValue(classType)) 
          .ToList(); 

但無論是給了我想要的結果。

在此先感謝

+0

只有''GetProperties()''應該可以工作 – 2015-04-01 16:43:27

+0

什麼,具體來說,是不是你的嘗試解決方案的工作? – Servy 2015-04-01 16:44:17

+1

看一看:[字段和C#中的屬性有什麼區別?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a -property-in-c) – 2015-04-01 16:46:55

回答

1

嘗試是這樣的:

using System; 
using System.Linq; 

public class Class1 
{ 
    public string ABC { get; set; } 
    public string DEF { get; set; } 
    public string GHI { get; set; } 
    public string JLK { get; set; } 
} 

class Program 
{ 
    static void Main() 
    { 
     // Do this if you know the type at compilation time 
     var propertyNames 
      = typeof(Class1).GetProperties().Select(x => x.Name); 

     // Do this if you have an instance of the type 
     var instance = new Class1(); 
     var propertyNamesFromInstance 
      = instance.GetType().GetProperties().Select(x => x.Name); 
    } 
} 
+0

乾淨和容易, 修改它爲var instance = Activator.CreateInstance(classType ); ,使其可以跨多個班級工作。 – 2015-04-01 16:53:55

+0

@ Devcon2將只適用於具有無參數構造函數的類嗎? – Mike 2015-04-01 17:10:45

+0

@Mike:不,我用這個用於重載構造函數的類。 – 2015-04-01 21:29:44

1

尚不明確表示在原始代碼什麼classType

如果它是應該工作的Class1的實例;如果你已經有System.Type,你的classType.GetType()不會返回你的屬性。

另外,您應該瞭解屬性和字段差異,因爲它對於反射非常重要。下面的代碼列出了您的原始屬性,跳過了一個沒有setter和一個字段的屬性,只是爲了演示概念差異如何影響您的代碼。

class Program 
{ 
    static void Main(string[] args) 
    { 
     var classType = typeof (Class1); 
     foreach (var prop in classType.GetProperties().Where(p => p.CanWrite)) 
     { 
      Console.WriteLine(prop.Name); 
     } 

     foreach (var field in classType.GetFields()) 
     { 
      Console.WriteLine(field.Name); 
     } 
    } 
} 

public class Class1 
{ 
    public string ABC { get; set; } 
    public string DEF { get; set; } 
    public string GHI { get; set; } 
    public string JLK { get; set; } 

    public string CantWrite { get { return ""; } } 
    public string Field = ""; 
} 
+0

@Downvoter,我在這裏錯過了什麼? – 2015-04-01 16:55:03

+0

我沒有downvote,但解釋通常是一個好主意。 – 2015-04-01 16:57:13

+0

夠公平的,我會提供的;謝謝 – 2015-04-01 16:59:55