简体   繁体   English

如何使用c#属性?

[英]How can I use c# attributes?

I have to create a pdf report from several classes that are going to contains several properties. 我必须从几个包含多个属性的类创建一个pdf报告。 I need to display the value of the propertie and a label in front of it. 我需要在其前面显示属性的值和标签。

Something like : 就像是 :

detailsCalcul : detailsCalcul:
Numero client : valueOfMyProperty. Numero客户端: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: 但是,如果您一个PropertyInfo和一个实例,则:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用属性来限制C#中接口方法的使用吗? - Can I use attributes to restrict usage of interface methods in C#? 如何在非ASP.NET网络环境中使用C#中的数据验证属性? - How can I use the Data Validation Attributes in C# in a non-ASP.net context? 如何在C#中使用自定义属性来替换交换机中的交换机? - How can I use custom-attributes in C# to replace switches in switches? 如何在不使用属性的情况下指定用于 MongoDB 反序列化的构造函数 (C#) - How can I specify the constructor to use for MongoDB deserialization without using attributes (C#) 如何使用C#读取.DLL文件的属性? - How can I read the attributes of a .DLL file using C#? C# 如何比较作为数组元素的对象的属性? - C# How can I compare objects' attributes that are elements of an array? 如何在C#中找到泛型类的属性? - How can I find the attributes of a generic class in C#? 如何通过两个属性查找元素? C#Web驱动程序 - How can I find element by two attributes? c# webdriver 如何使用GeckoFX / C#获取所有HTML属性 - How can I get all HTML attributes with GeckoFX/C# C#:我可以或如何为方法参数指定属性吗? - C#: Can I or how to assign attributes to method parameters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM