about summary refs log tree commit diff
path: root/IrcStates/Extensions.cs
blob: 181ac80352dd9eff701739e4a6ba76169b813586 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace IrcStates
{
    public static class Extensions
    {
        public static Delegate CreateDelegate(this MethodInfo methodInfo, object target)
        {
            if (methodInfo == null) return null;

            var types = methodInfo.GetParameters().Select(p => p.ParameterType);

            Func<Type[], Type> getType;
            if (methodInfo.ReturnType == typeof(void))
            {
                getType = Expression.GetActionType;
            }
            else
            {
                getType = Expression.GetFuncType;
                types   = types.Concat(new[] {methodInfo.ReturnType});
            }

            return methodInfo.IsStatic
                ? Delegate.CreateDelegate(getType(types.ToArray()), methodInfo)
                : Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo);
        }

        public static void UpdateWith<TKey, TValue>(this Dictionary<TKey, TValue> dict, Dictionary<TKey, TValue> other)
        {
            if (dict == null || other == null || !other.Any()) return;

            foreach (var (key, value) in other) dict[key] = value;
        }
    }
}