简体   繁体   English

如何在某个订单中获取类中的属性名称列表

[英]How to get a list of property names in a class in certain a order

I have a class similar to: 我有一个类似于的类:

public class MyClass : MyBaseClass
{
        public string Field1 { get; set; }
        public string Field2 { get; set; }
        public string Field3 { get; set; }
        public string Field4 { get; set; }
}

public class MyBaseClass
{
        public string BaseField1 { get; set; }
        public string BaseField2 { get; set; }
        public string BaseField3 { get; set; }
        public string BaseField4 { get; set; }
}

I then created a method to pull the names from the class. 然后我创建了一个从类中提取名称的方法。

private void MyMethod<T>(List<T> listData) where T : class
{
    String[] fieldNames = Array.ConvertAll<PropertyInfo, String>(typeof(T).GetProperties(), delegate(PropertyInfo fo) { return fo.Name; });

    // Do something with the fieldNames array....
}

So when I get my array it would be in the following order: 所以当我得到我的数组时,它将按以下顺序:

Field1
Field2
Field3
Field4
BaseField1
BaseField2
BaseField3
BaseField4

I was wondering if it was possible to change the order so that the base class fields were first followed by the derived class fields? 我想知道是否可以更改顺序,以便基类字段首先跟随派生类字段?

Let's implement a simple method to get how deep is the class in the class hierarchy 让我们实现一个简单的方法来获得类层次结构中类的深度

null <- object <- ... <- MyBaseClass <- MyClass <- ...

Implementation 履行

// 0     - null
// 1     - object
// ...
// n     - MyBaseClass
// n + 1 - MyClass
// ...
private static int TypeLevel(Type type) {
  if (null == type)
    return 0;

  return TypeLevel(type.BaseType) + 1;
}

And then with a help of Linq sort by this criterium, the only little trick is to use DeclaringType - where (in which class) the property has been declared: 然后在这个标准的Linq帮助下,唯一的小技巧是使用DeclaringType - DeclaringType属性的位置(在哪个类中):

// fieldNames are actually properties' names
string[] fieldNames = typeof(MyClass)
  .GetProperties()
  .OrderBy(p => TypeLevel(p.DeclaringType)) // <- base first, derived last
  .ThenBy(p => p.Name) // <- let's organize properties within each class
  .Select(p => p.Name) 
  .ToArray();

Console.Write(string.Join(Environment.NewLine, fieldNames));

Outcome: 结果:

BaseField1
BaseField2
BaseField3
BaseField4
Field1
Field2
Field3
Field4

Finally, your method can be something like this: 最后,您的方法可以是这样的:

// we don't want any restictions like "where T : class"
private void MyMethod<T>(List<T> listData) {
  ...
  string[] fieldNames = typeof(T)
    .GetProperties()
    .OrderBy(p => TypeLevel(p.DeclaringType)) // <- base first, derived last
    .ThenBy(p => p.Name) // <- let's organize properties within each class
    .Select(p => p.Name)
    .ToArray();

  ...
}

You will have to write some code like below to traverse the class hierarchy and then obtain the properties 您将不得不编写如下代码来遍历类层次结构,然后获取属性

static void GetProperties(Type type, List<string> returnValue) {
    var props = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
    returnValue.AddRange(props.Select(p => p.Name).OrderBy(p => p));
}

private void MyMethod<T>(List<T> listData) where T : class {
    var type = typeof(T);
    List<string> properties = new List<string>();
    while (type != null) {
        GetProperties(type, properties);
        type = type.BaseType;
    }
}

Select all properties of base class and union with all properties of derived class. 选择基类的所有属性,并使用派生类的所有属性进行联合。 The Distinct() will remove all duplicates. Distinct()将删除所有重复项。 If more complexity is needed you will have to try @Vikhram solution. 如果需要更多复杂性,您将不得不尝试@Vikhram解决方案。

        var properties = typeof(MyBaseClass).GetProperties().Select(x => x.Name)
            .Union(typeof(MyClass).GetProperties().Select(x => x.Name)).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过类中的属性排序类列表 - How to order a class list by a property within the classes 从类中获取要在查询字符串中使用的 JSON 属性名称列表 - Get a list of JSON property names from a class to use in a query string 基于类对象列表,如何创建有效属性名称列表? - Based on a list of class objects, how to create a list of valid property names? 如何获取类字段名称的列表 - How to get a list of names of class fields C# 中的通用函数,它采用随机类列表和某些属性名称的数组作为参数 - A generic function in C# that take a List of random class and an array of certain property names as parameters 如何按子类属性为父类列表排序? - How to do order by child class property for a list of parent class? 如何使用属性名称列表来验证类层次结构的属性 - How to validate the properties of a class hierarchy with a list of property names Roslyn - 如何使用 Roslyn 在 class 中获取属性名称和类型? - Roslyn - how to get property names and types in a class using Roslyn? 如何从未声明的类型中获取类和属性名称和值 - How to get class and property names and values from undeclared type 如何获取属性基于某种类型的类的所有属性 - How to get all properties of a class where the property is based on a certain type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM