3

私はいくつかの単体テストを書いており、フォームの関数がたくさんあります

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

私がやりたいのは、Action デリゲートを受け取り、さまざまな引数すべてでデリゲートを呼び出すことができる関数を作成することです。それを行う方法はありますか?

答え:

MichaelCG のおかげで、私がやったことは次のとおりです。

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

私はまだもっと一般的な方法に興味がありますが、これは私の目的には機能的です。

4

1 に答える 1

6

私があなたを正しく理解していれば、これはあなたが何をしようとしているのかを示すはずです. 魔法は 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>
于 2009-10-29T18:53:46.030 に答える