簡體   English   中英

在 GetMethod 中處理泛型類型

[英]Handle generic types in GetMethod

AddService(services, type, instance) 中正確定義通用版本的 GetMethod 參數是什么(以防萬一會出現更多重載)。

我知道我可以保持不同的方法名稱,但我不想。

目前,由於找到了多個方法版本,我得到了 null 或異常...

編碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM