通过反射的方式来执行静态类的泛型方法

今天在公司写代码的时候发生了一个问题;

被调用代码如下:

public static class CatalogComposition
    {
        private static AggregateCatalog catalogs = new AggregateCatalog();

        public static AggregateCatalog AggregateCatalog
        {
            get { return catalogs; }
        }

        public static void ComposeParts<T>(T t)
        {
            CompositionContainer compositionContainer = new CompositionContainer(AggregateCatalog);
            try
            {
                compositionContainer.ComposeParts(t);
            }
            catch (CompositionException ce)
            {
                throw new CompositionException(ce.Message, ce.InnerException);
            }
        }
    }

下面是没有纠正错误前的反射代码:

红色代码为错误代码。
抛出的异常为: 不能对 ContainsGenericParameters 为 True 的类型或方法执行后期绑定操作。
 try
            {
                if (viewModel == null)
                {
                    throw new ArgumentNullException("viewModel");
                }
                Type catalogComposition = Assembly.Load(ManifestConst.ARCHSTAR_FRAMEWORK_MEF).GetType(ManifestConst.ARCHSTAR_FRAMEWORK_MEF_CATALOGCOMPOSITION);
                MethodInfo composePartsMethod = catalogComposition.GetMethod("ComposeParts", BindingFlags.Static | BindingFlags.Public);
                composePartsMethod.Invoke(catalogComposition, new object[] { viewModel });
            }
            catch (ArgumentNullException ane)
            { }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

下面是正确的代码:

protected void ComposeParts(V viewModel)
        {
            try
            {
                if (viewModel == null)
                {
                    throw new ArgumentNullException("viewModel");
                }
                Type catalogComposition = Assembly.Load(ManifestConst.ARCHSTAR_FRAMEWORK_MEF).GetType(ManifestConst.ARCHSTAR_FRAMEWORK_MEF_CATALOGCOMPOSITION);
                MethodInfo composePartsMethod = catalogComposition.GetMethod("ComposeParts", BindingFlags.Static | BindingFlags.Public);
                composePartsMethod.MakeGenericMethod(new Type[] { typeof(V) }).Invoke(catalogComposition, new object[] { viewModel });
            }
            catch (ArgumentNullException ane)
            { }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

原文地址:https://www.cnblogs.com/dyllove98/p/3123020.html