C#动态函数AmbigiousMatchException?

我正在为调用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);

我究竟做错了什么?我该如何纠正这个?

解决方法:

看起来你不必要地使事情复杂化.无论何时将函数添加到列表中,函数及其参数都是已知的.您是否考虑过使用这样的匿名函数?作为一个例子,我已经包装了这个对象..这个例子中的字符串参数. 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);
        }
    }

如果严格不需要类型,你可以进一步简单地说它

 public partial class IBaseEvent
{
    public Action MyAction;


    public void Execute()
    {
        MyAction();
    }

    public void AddFunction(Action ff)
    {
        MyAction += ff;
    }
}
上一篇:引起 Edge 浏览器远程代码执行漏洞的 PoC 已发布


下一篇:c# – 使用依赖注入管理HttpClient的多个实例