C#委托和属性语法问题

Rah*_*hul 5 c# syntax

我有一个Dictionary [string,handler_func]类型的字典,其中
handler_func是一个类型的委托

public delegate void HANDLER_FUNC(object obj, TcpClient client);
Run Code Online (Sandbox Code Playgroud)

现在我有一个像这样的属性类

[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; }
    }

}
Run Code Online (Sandbox Code Playgroud)

基本的想法是我将此属性应用于类中的方法,并在某处使用反射来填充上面的Dictionary

问题是除非这种方法是静态的,否则atrribute不能正常工作

[MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)]
private void HandleLoginResponse(object obj, TcpClient client)  
Run Code Online (Sandbox Code Playgroud)

导致标准需要一个对象的东西
所以我的选择是什么(我不希望处理程序方法是静态的)谢谢

Tho*_*que 6

[MessageHandlerAttribute("HandleLoginResponse",HandleLoginResponse)]
private void HandleLoginResponse(object obj, TcpClient client)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么你需要在属性中指定方法:因为属性应用于方法,你已经可以检索方法......你可以这样做:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)