简体   繁体   English

C# 遍历类属性并添加以列出某些类型

[英]C# iterate through class properties and add to list certain types

EDIT I am sorry, my question was not clear.编辑对不起,我的问题不清楚。 I want to add to the list not only the property name but its value我想添加到列表中,不仅是属性名称,还有它的值

I want to iterate through all the properties of a class and find all properties of a certain type and add them to a list.我想遍历一个类的所有属性并找到某种类型的所有属性并将它们添加到列表中。 The code I use to iterate is:我用来迭代的代码是:

List<CustomAttribute> attributes = new List<CustomAttribute>();
PropertyInfo[] properties = typeof(CustomClass).GetProperties();

foreach (PropertyInfo property in properties)
{
    if (property.PropertyType == typeof(CustomAttribute))
    {
        //here I want to add property to list
    }
}

Any ideas?有任何想法吗?

Thanks谢谢

public static List<PropertyInfo> PropertiesOfType<T>(this Type type) =>
    type.GetProperties().Where(p => p.PropertyType == typeof(T)).ToList();

And you'd use it as follows:您可以按如下方式使用它:

var properties = typeof(CustomClass).PropertiesOfType<CustomAttribute>();

If what you need are the values of the properties of type T in a given instance then you could do the following:如果您需要的是给定实例中T类型属性的,那么您可以执行以下操作:

 public static List<T> PropertyValuesOfType<T>(this object o) =>
        o.GetType().GetProperties().Where(p => p.PropertyType == typeof(T)).Select(p => (T)p.GetValue(o)).ToList();

And you'd use it as:您可以将其用作:

CustomClass myInstance = ...
var porpertyValues = myInstance.GetPropertyValuesOfType<CustomAttribute>();

Note that this just gives you the idea, you need to evaluate if dealing with properties with no getters is needed.请注意,这只是给您一个想法,您需要评估是否需要处理没有 getter 的属性。

And last but not least, if you need the values and the property names, then you can build up a List of tuples to store the information:最后但并非最不重要的是,如果您需要值属性名称,那么您可以构建一个元组List来存储信息:

public static List<Tuple<string, T>> PropertiesOfType<T>(this object o) =>
        o.GetType().GetProperties().Where(p => p.PropertyType == typeof(T)).Select(p => new Tuple<string, T>(p.Name, (T)p.GetValue(o))).ToList();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM