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
[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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With