attributes are like properties of the Type or the member. and are not data in an instance.
suppose I have the following classes:
public class UserData1
{
public string Text { get; set;}
public string Name { get; set;}
public string Address { get; set;}
}
public class UserData2
{
public string Description { get; set;}
public double Price { get; set;}
public string StorageLocation { get; set;}
}
and suppose I have a reporting Utility, that wants to print out some of the properties.
I could go by implementing a ReportMe interface for each class, or an interface for each class, that only exposed the properties that I want.
with attributes, I can define
public class ReportableAttribute : Attribute {}
now you can mark classes and properties with this attribute:
[Reportable]
public class UserData1
{
[Reportable]
public string Text { get; set;}
[Reportable]
public string Name { get; set;}
public string Address { get; set;}
}
[Reportable]
public class UserData2
{
[Reportable]
public string Description { get; set;}
[Reportable]
public double Price { get; set;}
public string StorageLocation { get; set;}
}
now I can query an object, and all it's properties if they have this attribute
public void ReportObject(object target)
{
bool report = false;
foreach (Attribute a in target.GetCustomAttributes())
{
if (a is ReportableAttribute)
{
report = true;
break;
}
}
if (report )
{
PropertyInfo[] infos = target.GetType().GetProperties (BindingFlags.Public | BindingFlags.Instance | GetField);
foreach (var propInf in infos)
{
foreach (Attribute b in propInf .GetCustomAttributes(false))
{
if(b is ReportableAttribute)
{
this.Writer.Append(propInf.GetValue(target));
break;
}
}
}
}
}