[英]Find generic object property attribute value using reflection at run time
I created a custom attribute class that I use to control certain aspect when I export an object to CSV format. 我创建了一个自定义属性类,用于在将对象导出为CSV格式时控制某些方面。
[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
public bool Exportable { get; set; }
public string ExportName{ get; set; }
}
Here is an example of one of the object I want to export: 这是我要导出的对象之一的示例:
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; }
}
I create my Export function that accept a generic object. 我创建接受通用对象的Export函数。
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
}
}
My question is how can I use reflection to find if the property has the attribute "Exportable" and that if it is true? 我的问题是如何使用反射来查找该属性是否具有“可导出”属性,以及该属性是否为true?
Please note I can pass in any generic object, in this case I want my final export to contain one column that contains PropertyA data and that my column header value is "Column A" 请注意,我可以传入任何通用对象,在这种情况下,我希望最终导出包含一个包含PropertyA数据的列,并且我的列标题值为“ Column A”
You are on the right path, replace the froeach body with this: 您在正确的道路上,将泡沫体替换为:
var attribute = property.GetCustomAttribute<MyCustomAttribute>();
if(attribute != null)
{
bool isExportable = attribute.Exportable;
// rest of the code
}
@Sohaib Jundi gave a very good answer. @Sohaib Jundi给出了很好的答案。 If, for some reason, you decide to create more Custom Attributes, you can do somethink similar to this:
如果出于某种原因决定创建更多自定义属性,则可以执行以下类似操作:
public void Export<T>(T exportObject)
{
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var attributes = Attribute.GetCustomAttributes(property, false);
foreach (var attribute in attributes)
{
if (attribute is MyCustomAttribute)
{
if (((MyCustomAttribute)attribute).Exportable)
{
}
}
if (attribute is MyCustomAttribute2)
{
if (((MyCustomAttribute2)attribute).AnotherThing)
{
}
}
}
}
}
This way you could check for multiple attributes of your object 这样,您可以检查对象的多个属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.