C#迭代类属性并添加到特定类型的列表中
编辑 对不起,我的问题不清楚。我不仅要将属性名称添加到列表中,还要将其值添加到列表中 我想遍历一个类的所有属性,找到某个类型的所有属性,并将它们添加到列表中。我用来迭代的代码是:C#迭代类属性并添加到特定类型的列表中,c#,reflection,C#,Reflection,编辑 对不起,我的问题不清楚。我不仅要将属性名称添加到列表中,还要将其值添加到列表中 我想遍历一个类的所有属性,找到某个类型的所有属性,并将它们添加到列表中。我用来迭代的代码是: List<CustomAttribute> attributes = new List<CustomAttribute>(); PropertyInfo[] properties = typeof(CustomClass).GetProperties(); foreach (PropertyI
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
}
}
List attributes=newlist();
PropertyInfo[]properties=typeof(CustomClass).GetProperties();
foreach(属性中的PropertyInfo属性)
{
if(property.PropertyType==typeof(CustomAttribute))
{
//在这里,我想将属性添加到列表中
}
}
有什么想法吗
谢谢
您可以将其用作:
CustomClass myInstance = ...
var porpertyValues = myInstance.GetPropertyValuesOfType<CustomAttribute>();
您想添加特定类型的属性吗?是的,我只想在列表中添加特定类型的属性是
CustomAttribute
CustomAttribute还是普通类型?不,它是自定义类
var properties = typeof(CustomClass).PropertiesOfType<CustomAttribute>();
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();
CustomClass myInstance = ...
var porpertyValues = myInstance.GetPropertyValuesOfType<CustomAttribute>();
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();