How to use a variable as a method name using dynamic objects

后端 未结 4 830
迷失自我
迷失自我 2021-01-02 16:16

In SignalR there is public property defined in the HubConnectionContext as such:

public dynamic All { get; set; }

This enables users to cal

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 17:12

    While I love all the fun reflection answers, there's a much simpler and faster way to invoke client hub methods using a string as the method Name.

    Clients.All, Clients.Others, Clients.Caller, Clients.AllExcept(connectionIds), Clients.Group(groupName), Clients.OthersInGrouop(groupName), and Clients.Client(connectionId) are all dynamic objects, but they also all implement the IClientProxy interface.

    You can cast any of these dynamic objects to an IClientProxy, and then call Invoke(methodName, args...):

    public void AcceptSignal(string methodToCall, string msg)
    {
    
        IClientProxy proxy = Clients.All;
        proxy.Invoke(methodToCall, msg);
    }
    

提交回复
热议问题