How to call a generic extension method with reflection?

后端 未结 4 1757
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 17:30

I wrote the extension method GenericExtension. Now I want to call the extension method Extension. But the value of methodInfo is alway

4条回答
  •  隐瞒了意图╮
    2020-12-06 17:56

    In case you have an extension method like

    public static class StringExtensions
    {
        public static bool IsValidType(this string value);
    }
    

    you can invoke it (e. g. in tests) like so:

    public class StringExtensionTests
    {
        [Theory]
        [InlineData("Text", typeof(string), true)]
        [InlineData("", typeof(string), true)]
        [InlineData("Text", typeof(int), false)]
        [InlineData("128", typeof(int), true)]
        [InlineData("0", typeof(int), true)]
        public void ShouldCheckIsValidType(string value, Type type, bool expectedResult)
        {
            var methodInfo = 
                typeof(StringExtensions).GetMethod(nameof(StringExtensions.IsValidType),
                new[] { typeof(string) });
            var genericMethod = methodInfo.MakeGenericMethod(type);
            var result = genericMethod.Invoke(null, new[] { value });
            result.Should().Be(expectedResult);
        }
    }
    

提交回复
热议问题