Question of delegate syntax and C # attributes

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

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

I now have an attribute class similar to

[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 main idea is that I apply this attribute to a method in the class, and somewhere I use reflection to populate the Dictionary above

The problem is that if this method is not static, then the atrribute attribute does not work therefore

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

causes a standard need for an object thing
So what are my parameters (I don't want the handler method to be static) Thanks

+5
source share
6 answers
[MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)]
private void HandleLoginResponse(object obj, TcpClient client)

, : , ... - :

[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);
    }
}
+6

, (HandleLoginResponse - , , )

+2

... , , .

, ( target Delegate.CreateDelegate ), ( , param0 - ​​ ).

, , ( 100% ).

+2

, typeof .

+2

, !

, , atrribute ...

. , HandleLoginResponse , ?

, . const, .

+2

Earwicker: , ... . :

error CS0182: The attribute argument must be a constant expression, a type expression, or an array expression of the attribute parameter type

What I'm trying to do is to specify a specific method that is called when the property changes. This would be helpful with the help of a delegate. I worked with this line yesterday, but it is too weak ... using a static method would be better, but this seems impossible in the current version of the .NET Framework (3.5, VS2008).

Too bad!

+2
source

All Articles