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

后端 未结 4 816
迷失自我
迷失自我 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:19

    You can use reflection to find the method. But this will only work if it is a "real" non-dynamic method which is defined in the usual non-dynamic way, only hidden behind the dynamic keyword.

    If however the object All is truely dynamic, like an ExpandoObject or something else deriving from System.Dynamic.DynamicObject, the "method" could be something that was only associated with the type at runtime, and in that case typeof(All).GetMethod won't find anything.

    It was Ilya Ivanov who originally pointed this out, in a comment to John Willemse's answer. It became apparent that the object is a Microsoft.AspNet.SignalR.Hubs.ClientProxy instance.

    Therefore, from the documentation of that type, the solution is:

    string methodToCall = XXX;
    string msg = YYY;
    ((ClientProxy)(Clients.All)).Invoke(methodToCall, msg);
    

提交回复
热议问题