代码之家  ›  专栏  ›  技术社区  ›  Bryan Anderson

创建泛型函数的委托

  •  3
  • Bryan Anderson  · 技术社区  · 15 年前

    我正在写一些单元测试,我有很多表单的功能

    public void SomeTestHelperMethod<TKey, TValue>(TKey key, TValue value)
    

    我用各种各样的论据反复打电话

    SomeTestHelperMethod<int, int>(0, 1);
    SomeTestHelperMethod<int, object>(1, new Nullable<double>(16.5));
    SomeTestHelperMethod<int, string>(2, "The quick brown fox jumped over the lazy dog.");
    SomeTestHelperMethod<object, int>(new NullReferenceException(), 15);
    SomeTestHelperMethod<object, object>(StringComparison.Ordinal, new Version());
    SomeTestHelperMethod<object, string>((ushort)3, string.Empty);
    SomeTestHelperMethod<string, int>(string.Empty, 195);
    SomeTestHelperMethod<string, object>("A string", this);
    SomeTestHelperMethod<string, string>("Another string", "Another string");
    

    我要做的是编写一个函数,该函数接受一个动作委托,并且可以用所有不同的参数调用委托。有什么办法吗?

    答:

    多亏了迈克尔,我终于做到了:

    private void CallWithKeyAndValue(string methodName)
    {
        MethodInfo method = typeof(ObservableDictionaryTest).GetMethod(methodName);
        foreach (KeyValuePair<object, object> kvp in ourKeyValueSet)
        {
            MethodInfo genericMethod = method.MakeGenericMethod(kvp.Key.GetType(), kvp.Value.GetType());
            genericMethod.Invoke(this, new[] { kvp.Key, kvp.Value });
        }
    }
    

    我仍然对一个更通用的方法感兴趣,但这个方法对于我的目的是有用的。

    1 回复  |  直到 15 年前
        1
  •  6
  •   MichaelGG    15 年前

    如果我正确理解你,这应该说明你在做什么。魔法在makegenericmethod中。

    using System;
    
    class Program {
        static void Main(string[] args) {
            var meth = typeof(Program).GetMethod("Meth");
            var items = new[] { 
                new { a = (object)"hi", b = (object)1 },
                new { a = (object)TimeSpan.MaxValue, b = (object)DateTime.UtcNow },
            };
            foreach (var item in items) {
                var gmeth = meth.MakeGenericMethod(item.a.GetType(), item.b.GetType());
                gmeth.Invoke(null, new[] { item.a, item.b });
            }
        }
    
        public static void Meth<A, B>(A a, B b) {
            Console.WriteLine("<{0}, {1}>", typeof(A).Name, typeof(B).Name);
        }
    }
    

    输出:

    <String, Int32> 
    <TimeSpan, DateTime>