c#动态函数AmbigiousMatchException
本文关键字:AmbigiousMatchException 函数 动态 | 更新日期: 2023-09-27 18:15:05
我得到一个调用Type.GetMethod()的函数的AmbigiousMatchException,尽管一切看起来都很正确。
public partial class IBaseEvent
{
private Dictionary<int, Func<object[], object>> funcs = new Dictionary<int,Func<object[],object>>();
private Dictionary<int, object[]> func_args = new Dictionary<int,object[]>();
public void Execute()
{
int exp = 0;
foreach(var func in funcs)
{
exp = func.GetHashCode();
func.Value.DynamicInvoke(func_args[exp]);
}
}
public void AddFunction(Type T, dynamic sFunc, params object[] parameters)
{
funcs.Add(T.GetHashCode(), new Func<object[],object>(T.GetMethod(sFunc)));
func_args.Add(T.GetHashCode(), parameters);
}
}
public class DummyEvent : IBaseEvent
{
private string EventType = "DUMMY_EVENT";
public DummyEvent()
{
object[] parm = new object[3];
parm[0] = Logging.LOG_TYPE.DEBUG;
parm[1] = "Hello World from DummyEvent! TypeCode: {0}";
parm[2] = typeof(DummyEvent).GetType().GUID;
AddFunction(typeof(Logging.LoggingFactory), "WriteToLog", parm);
}
}
AddFunction(typeof(Logging.LoggingFactory), "WriteToLog", parm);
我做错了什么?我该如何改正呢?
根据错误消息,我怀疑您可能已经在LoggingFactory或其继承链中有一个函数WriteToLog
。
你似乎把事情复杂化了。无论何时将函数添加到列表中,函数及其参数都是已知的。您是否考虑过像这样使用匿名函数?作为一个例子,我包装了这个对象…本例中的字符串参数。DynamicInvoke也会相当慢。
两种不同的类型也可以返回相同的GetHashCode,这取决于您的特定需求,可能重要,也可能不重要。
public partial class IBaseEvent
{
private Dictionary<int, Action> funcs = new Dictionary<int, Action>();
public void Execute()
{
foreach (var func in funcs.Values)
{
func();
}
}
public void AddFunction(Type t, Action ff)
{
funcs.Add(t.GetHashCode(), ff);
}
}
public class DummyEvent : IBaseEvent
{
private string EventType = "DUMMY_EVENT";
private void DoSomething(string x)
{
Console.WriteLine(x);
}
public DummyEvent()
{
Action temp = () =>
{
DoSomething("Hello World from DummyEvent! TypeCode");
};
AddFunction(typeof(Logging), temp);
}
}
如果严格不需要type,可以进一步简化如下
public partial class IBaseEvent
{
public Action MyAction;
public void Execute()
{
MyAction();
}
public void AddFunction(Action ff)
{
MyAction += ff;
}
}