Method based attributes used as delegates

  • Thread starter Thread starter msnews.microsoft.com
  • Start date Start date
M

msnews.microsoft.com

I am no expert on attributes, but I have used them, but I am stumped by this
one ...

basically is it possible to get the attributes from a method used as a
delegate?


For example, I have a method called

[TileSizeAttribute(40, 70)]
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
// stuff
}

that I am setting via ...

listView1.DrawItem =+ listView1_DrawItem

Then in DrawItem I would like to grab the TileSizeAttribute information, but
I don't seem to be getting it?

I have tried ...

public new event DrawListViewItemEventHandler DrawItem

{

add {

Type type = value.GetType();
TileSizeAttribute a =
(TileSizeAttribute)Attribute.GetCustomAttribute(type,
typeof(TileSizeAttribute));



but a is null ... Anyone have any suggestions how I should proceed?
 
msnews.microsoft.com said:
I am no expert on attributes, but I have used them, but I am stumped by this
one ...

basically is it possible to get the attributes from a method used as a
delegate?

Yup. here's a sample:

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

class Test
{
event EventHandler Foo
{
add
{
Console.WriteLine ("value={0}", value);
MethodInfo method = value.Method;
object[] attrs = method.GetCustomAttributes(false);
foreach (object attr in attrs)
{
Console.WriteLine ("Attribute: {0}", attr);
}
}
remove
{
}
}

static void Main()
{
Test t = new Test();

t.Foo += new EventHandler(Dummy);
}

[STAThread]
static void Dummy(object sender, EventArgs e)
{
}
}
 
Back
Top