在 GetMethod 中处理泛型类型

Handle generic types in GetMethod

AddService(services, type, instance) 中 GetMethod 的正确参数是什么,准确定义了通用版本(以防出现更多重载)。

我知道我可以保持方法名称不同,但我不想这样做。

目前由于找到多个方法版本,我得到空值或异常...

代码:

namespace Sample
{

    public interface IService { }

    public static class SampleExtensions
    {

        public static IServiceCollection AddService<T>(this IServiceCollection services, T instance) where T : IService
        {
            //services.AddSingleton<T>(instance);
            services.AddSingleton(instance.GetType(), instance); // register with the concrete implementation type
            //some stuff that only works with generic T
            return services;
        }

        public static IServiceCollection AddService(this IServiceCollection services, Type type, object instance)
        {

            Type classType = typeof(SampleExtensions);
            MethodInfo methodInfo = classType.GetMethod                         // correct arguments??
            (
                nameof(AddService),                                             // only name would bring 2 results
                new Type[] { typeof(IServiceCollection), typeof(object) }       // ??? instance is generic
            );
            MethodInfo genericMethod = methodInfo.MakeGenericMethod(type);
            genericMethod.Invoke(null, new[] { services, instance });           // call the generic method version
            return services;
        }

    }
}

您可以使用Type.MakeGenericMethodParameter来表示泛型参数引用:

MethodInfo methodInfo = classType.GetMethod                         
(
    nameof(AddService),                                             
    new Type[] { typeof(IServiceCollection), Type.MakeGenericMethodParameter(0) }      
);