p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   C# (http://p2p.wrox.com/forumdisplay.php?f=22)
-   -   Access to attribute values from class of attribute (http://p2p.wrox.com/showthread.php?t=34716)

jacob October 28th, 2005 12:06 PM

Access to attribute values from class of attribute
 
How do I retrieve the values of the attributes set on e.g. a class?

I have implemented a custom attribute, which is used for classes. Through the attribute it is possible to set different values. I want to get access to these values from within the class itself.

Is there a smart way of doing this, like accessing the values of an ordinary object?

Thanks, Jacob.

jacob October 28th, 2005 01:11 PM

I found a way but I am not sure it is the easiest way or the most cost-effective way. Here is the solution I found...
Code:

using System;
using System.Reflection;

namespace Test
{
    public class MyCustomAttribute : Attribute
    {
        public string item;

        public MyCustomAttribute()
        {
            this.item = item;
        }
    }

    [MyCustom(item="myitemvalue")]
    class MyClassWithTheAttributeApplied
    {
        public static void SomeMethod()
        {
            MemberInfo info = typeof(MyClassWithTheAttributeApplied);
            object[] o = info.GetCustomAttributes(true);
            foreach(object t in o)
                Console.WriteLine(((MyCustomAttribute)t).item);
        }
    }

    class MainClass
    {
        [STAThread]
        static void Main(string[] args)
        {
            MyClassWithTheAttributeApplied.SomeMethod();
        }
    }
}

The above code will output myitemvalue. Please comment on the post if you know a better way to do this. Thanks.

Jacob.


All times are GMT -4. The time now is 02:40 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.