今天在公司寫代碼的時候發生了一個問題;
被調用代碼如下:
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);
}
}