加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MEF:来自Type的GetExportedValue?

发布时间:2020-12-16 00:15:25 所属栏目:百科 来源:网络整理
导读:使用MEF我可以创建并加载这样的类型: var view = Container.GetExportedValueMyView(); 现在我想做的是: Type t = typeof(MyView);var view = Container.GetExportedValuet(); (当然,类型可能包含与MyView不同的内容). 使用泛型GetExportedValue这是不可能
使用MEF我可以创建并加载这样的类型:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读