
var vIEw = Container.GetExportedValue<MyVIEw>();
现在我想做的是:
Type t = typeof(MyVIEw);var vIEw = Container.GetExportedValue<t>();
(当然,类型可能包含与MyVIEw不同的内容).
使用泛型GetExportedValue<>这是不可能的. – 有没有其他方法来实现这一目标?
解决方法 你可以使用反射.这是一个例子:
using System;using System.ComponentModel.Composition;using System.ComponentModel.Composition.Hosting;using System.linq;using System.Reflection;namespace windowsFormsApplication1{ static class Program { [STAThread] static voID Main() { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(IMessage).Assembly)); CompositionContainer container = new CompositionContainer(catalog); Type t = typeof(IMessage); var m = container.GetExportedValue(t); } } public static class CompositionContainerExtension { public static object GetExportedValue(this ExportProvIDer container,Type type) { // get a reference to the GetExportedValue<T> method MethodInfo methodInfo = container.GetType().getmethods() .Where(d => d.name == "GetExportedValue" && d.GetParameters().Length == 0).First(); // create an array of the generic types that the GetExportedValue<T> method expects Type[] genericTypeArray = new Type[] { type }; // add the generic types to the method methodInfo = methodInfo.MakeGenericmethod(genericTypeArray); // invoke GetExportedValue<type>() return methodInfo.Invoke(container,null); } } public interface IMessage { string Message { get; } } [Export(typeof(IMessage))] public class MyMessage : IMessage { public string Message { get { return "test"; } } }} 总结 以上是内存溢出为你收集整理的c# – MEF:来自Type的GetExportedValue?全部内容,希望文章能够帮你解决c# – MEF:来自Type的GetExportedValue?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)