I have a ShowAttribute
and I am using this attribute to mark some properties of classes. What I want is, printing the values by the properties that has a Name attribute. How can I do that ?
public class Customer
{
[Show("Name")]
public string FirstName { get; set; }
public string LastName { get; set; }
public Customer(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
class ShowAttribute : Attribute
{
public string Name { get; set; }
public ShowAttribute(string name)
{
Name = name;
}
}
I know how to check the property has a ShowAttribute or not, but I couldnt understand how to use it.
var customers = new List<Customer> {
new Customer("Name1", "Surname1"),
new Customer("Name2", "Surname2"),
new Customer("Name3", "Surname3")
};
foreach (var customer in customers)
{
foreach (var property in typeof (Customer).GetProperties())
{
var attributes = property.GetCustomAttributes(true);
if (attributes[0] is ShowAttribute)
{
Console.WriteLine();
}
}
}
Console.WriteLine(property.GetValue(customer).ToString());
However, this will be pretty slow. You can improve that with GetGetMethod
and creating a delegate for each property. Or compile an expression tree with a property access expression into a delegate.
You can try the following:
var type = typeof(Customer);
foreach (var prop in type.GetProperties())
{
var attribute = Attribute.GetCustomAttribute(prop, typeof(ShowAttribute)) as ShowAttribute;
if (attribute != null)
{
Console.WriteLine(attribute.Name);
}
}
The output is
Name
If you want the value of the property:
foreach (var customer in customers)
{
foreach (var property in typeof(Customer).GetProperties())
{
var attributes = property.GetCustomAttributes(false);
var attr = Attribute.GetCustomAttribute(property, typeof(ShowAttribute)) as ShowAttribute;
if (attr != null)
{
Console.WriteLine(property.GetValue(customer, null));
}
}
}
And the output is here:
Name1
Name2
Name3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With