【发布时间】:2019-07-12 17:20:26
【问题描述】:
我创建了一个自定义属性类,用于在将对象导出为 CSV 格式时控制某些方面。
[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
public bool Exportable { get; set; }
public string ExportName{ get; set; }
}
这是我要导出的对象之一的示例:
public class ObjectA
{
[MyCustom(Exportable = true, ExportColumnName = "Column A")]
public string PropertyA {get; set; }
[MyCustom(Exportable = false)]
public string PropertyB {get; set; }
public string PropertyC {get; set; }
}
我创建了接受通用对象的导出函数。
public void Export<T>(T exportObject)
{
//I get the property name to use them as header
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
//find the list of attribute of this property.
var attributes = Attribute.GetCustomAttributes(property, false);
//if attribute "Exportable" value is false or doesn't exists then continue foreach
//else continue export logic
}
}
我的问题是如何使用反射来查找属性是否具有“可导出”属性以及是否为真?
请注意,我可以传入任何通用对象,在这种情况下,我希望我的最终导出包含一个包含 PropertyA 数据的列,并且我的列标题值为“列 A”
【问题讨论】:
标签: c# .net reflection