通過反射的方式來執行靜態類的泛型方法


今天在公司寫代碼的時候發生了一個問題;

 

被調用代碼如下:

 

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM