C # dynamic function AmbigiousMatchException?

I get an AmbigiousMatchException for a function that calls Type.GetMethod (), although everything looks pretty correct.

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

Errors in AddFunction (typeof (Logging.LoggingFactory), "WriteToLog", parm);

What am I doing wrong? and how can i fix this?

+4
source share
2 answers

It seems like you overly complicate things. Both the function and its argument are known when you add them to the list. You considered using anonymous functions. As an example, I wrapped this object .. the string argument in this example. DynamicInvoke will also be significantly slower.

Also, two different types can return the same GetHashCode , which, depending on your specific needs, may or may not matter.

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

If the type is not strictly needed, you can just like that

  public partial class IBaseEvent { public Action MyAction; public void Execute() { MyAction(); } public void AddFunction(Action ff) { MyAction += ff; } } 
+1
source

Based on the error message, I suspect that you already have the WriteToLog function in the LoggingFactory or inheritance chain.

+2
source

Source: https://habr.com/ru/post/1382004/


All Articles