【发布时间】:2020-05-04 10:07:09
【问题描述】:
正如标题所说,使用反射我得到了具有给定属性的类型的方法。然后我想存储该对象实例的该方法,以便以后可以调用它。我不确定如何将该方法与该实例一起存储在包含 Action 的字典中。消息是字典中的关键用途。所有具有此属性的方法都需要采用 1 个动态类型的参数。
static Dictionary<string, Action<dynamic>> networkHooks = new Dictionary<string, Action<dynamic>>();
private static void RegisterNetworkMethods(Type type, INetworkEnabled obj)
{
// get the methods of this type that have the NetworkMethodAttribute
var methods = (from m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
where m.GetCustomAttributes(false).OfType<NetworkMethodAttribute>().Count() > 0
select m).ToList();
foreach(var method in methods)
{
// get the NetworkMethodAttribute Message variable that was assigned
var message = method.GetCustomAttribute<NetworkMethodAttribute>().Message;
// todo: store this instance method in an Action somehow so it can be called later
// networkHooks.Add(message, ???);
}
}
【问题讨论】:
-
看起来您正在走上正轨...您只需将
MethodInfo method转换为Action<dynamic> @delegate并存储它...这里有一个链接可以帮助您。 stackoverflow.com/questions/3021578/… -
您是否使用
Action<dynamic>,因为该方法可以采用任何类型的参数?
标签: c# reflection