Attributes in C#
February 20, 2006 10:47 AM
Subscribe
Attributes in .NET (C#): From within a class, how do I find all the methods marked with an attribute and fire those methods?
I've found a number of links on attributes in C#, but they all show how to mark items in a class with an attribute and then look that info up from a small console application. I've managed to create an attribute (amazing, I know), but what I want to do is create a method in an abstract parent class that will fire all methods in a sub-class marked with my shiny new attribute. And that part's not happening.
posted by yerfatma to computers & internet (9 comments total)
using System;
using System.Reflection;
namespace AttributeTester
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Class1 c = new Class1();
c.GetMyAttributes();
}
public void Test1(int a)
{
}
[MyAttribute]
public void Test3(int a)
{
}
public void GetMyAttributes()
{
MemberInfo[] members = typeof(Class1).FindMembers(
MemberTypes.All,
BindingFlags.Instance | BindingFlags.Public,
new MemberFilter(FilterMembersByAttributeType),
typeof(MyAttribute));
foreach (MemberInfo mi in members)
{
Console.WriteLine(mi.Name);
}
}
private static bool FilterMembersByAttributeType(MemberInfo info, object state)
{
Type desired_attribute_type = (Type) state;
object[] attrs = info.GetCustomAttributes(desired_attribute_type, false);
return (0 < attrs.length);br> }
}
[AttributeUsage(AttributeTargets.Method)]
class MyAttribute : Attribute
{
}
}
>
posted by chos at 12:41 PM on February 20, 2006