【问题标题】:Handle generic types in GetMethod在 GetMethod 中处理泛型类型
【发布时间】:2021-10-22 08:39:25
【问题描述】:

正确定义通用版本的 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;
        }

    }
}

【问题讨论】:

标签: c# generics reflection


【解决方案1】:

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

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

【讨论】:

  • 在我的情况下它不起作用 - Get public static void AddLink&lt;T0&gt;(UnityAction&lt;T0&gt; unityAction, UnityEvent&lt;T0&gt; unityEvent) { } By myClassType.GetMethod("AddLink", new Type[] {Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0)}
  • @DenisSivtsov 那是因为你的参数不是T0,而是UnityAction&lt;T0&gt;UnityEvent&lt;T0&gt;
猜你喜欢
  • 2019-05-20
  • 2023-03-15
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 2018-09-29
  • 2010-09-15
  • 1970-01-01
  • 2013-10-19
相关资源
最近更新 更多