Dynamically set generic type argument

后端 未结 2 1956
刺人心
刺人心 2021-01-05 15:01

Following on from my question here, I\'m trying to create a generic value equality comparer. I\'ve never played with reflection before so not sure if I\'m on the right track

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 15:53

    You need to call the method using reflection, like this:

    MethodInfo genericMethod = typeof(SomeClass).GetMethod("ContainSameValues");
    MethodInfo specificMethod = genericMethod.MakeGenericMethod(p1.GetType());
    if (!(bool)specificMethod.Invoke(this, new object[] { p1, p2 }))
    

    However, your method should not be generic in the first place; it should simply take two object parameters. (Or, if it is generic, it should cache properties and delegates in a generic type)

提交回复
热议问题