简体   繁体   中英

How can I use c# attributes?

I have to create a pdf report from several classes that are going to contains several properties. I need to display the value of the propertie and a label in front of it.

Something like :

detailsCalcul :
Numero client : valueOfMyProperty.

...

I was thinking of doing something like this :

[NomRapport("detailsCalcul")]
public class MyClass
{
    [NomChamp("Numero client")]
    public string NumeroClient { get; set; }
}

I sucessfully acessed to the value of my two attributes :

System.Reflection.MemberInfo[] proprietes = typeof(MyClass).GetMembers();
MyClass client = new MyClass();
client.NumeroClient = "1234";
        foreach (var p in proprietes)
        {
            var aa = p.GetCustomAttributes(true);
            for (int i = 0; i < aa.Length; i++)
            {
                var test = aa[i];
                if (test.GetType() == typeof(NomChampAttribute))
                { 
                  var nomChamp = ((NomChampAttribute)attributes[i]).ToString());
                }
            }
        }

i would like to know if it is possible access to the value of my property while I am acessing to the attribute ?

Thanks for your help,

Guillaume

An attribute does not know the context to which it is applied; you cannot even get to the property, let alone the instance. However, if you have a PropertyInfo and an instance, then:

object value = property.GetValue(instance, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM