2015-04-01 176 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