Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# delegate and attributes syntax question

Tags:

syntax

c#

I have a dictionary which is of type Dictionary [string,handler_func] where
handler_func is a delegate of type

public delegate void HANDLER_FUNC(object obj, TcpClient client);

now I have an attribute class like so

[AttributeUsage(AttributeTargets.Method)]
public class MessageHandlerAttribute : Attribute
{

    public MessageHandlerAttribute(string s1, HANDLER_FUNC hf)
    {
        s1 = name;
        msgtype = hf;
    }
    private string name;
    public string HandlerName
    {
        get { return name; }
        set { name = value; }
    }

    private HANDLER_FUNC msgtype;
    public HANDLER_FUNC MessageName
    {
        get { return msgtype; }
        set { msgtype = value; }
    }

}

The basic idea is I apply this attribute to a method in a class and somewhere I use reflection to fill up the Dictionary above

problem is unless this method is static the atrribute is not working so

[MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)]
private void HandleLoginResponse(object obj, TcpClient client)  

is causing the standard need an object thing
So what are my options ( i do not want the handler method to be static ) Thanks

like image 683
Rahul Avatar asked Jul 30 '09 08:07

Rahul


1 Answers

[MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)]
private void HandleLoginResponse(object obj, TcpClient client)

I don't understand why you need to specify the method in the attribute : since the attribute is applied to the method, you can already retrieve the method... You could do something like that :

[MessageHandlerAttribute("HandleLoginResponse")]
private void HandleLoginResponse(object obj, TcpClient client)

...

foreach(MethodInfo method in this.GetType().GetMethods())
{
    MessageHandlerAttribute attr = Attribute.GetCustomAttribute(method, typeof(MessageHandlerAttribute)) as MessageHandlerAttribute;
    if (attr != null)
    {
        HANDLER_FUNC func = Delegate.CreateDelegate(typeof(HANDLER_FUNC), this, method) as HANDLER_FUNC;
        handlers.Add(attr.HandlerName, func);
    }
}
like image 82
Thomas Levesque Avatar answered Oct 13 '22 05:10

Thomas Levesque