从任何类中获取字段(基于类型)

时间:2015-04-01 16:41:30

标签: c#

我有一个班级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();

但是没有给我想要的结果。

提前致谢

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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 = "";
}