当前位置: 首页 > 编程语言 > C#

MEFGetExports使用AllowMultiple=True时不返回任何内容

时间:2023-04-10 19:54:09 C#

MEFGetExports使用AllowMultiple=True时不返回任何内容我正在尝试使用MEF获取有关类及其使用方法的一些信息。我正在使用元数据选项来尝试实现这一点。我的界面和属性如下所示:publicinterfaceIMyInterface{}publicinterfaceIMyInterfaceInfo{TypeSomeProperty1{get;}双SomeProperty2{得到;}字符串SomeProperty3{得到;}}[元数据属性][AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]publicclassExportMyInterfaceAttribute:ExportAttribute,IMyInterfaceInfo{publicExportMyInterfaceAttribute(TypesomeProperty1,doublesomeProperty2,stringsomeProperty3):base(typeof(IMyInterface)){SomeProperty1=someProperty1;一些属性2=一些属性2;一些属性3=一些属性3;}publicTypeSomeProperty1{get;放;}publicdoubleSomeProperty2{get;放;}publicstringSomeProperty3{get;放;用这个属性装饰的类如下:[ExportMyInterface(typeof(string),0.1,"whoodata!")][ExportMyInterface(typeof(int),0.4,"asdfasdf!!")]publicclassDecoratedClass:IMyInterface{}尝试像这样使用导入的方法:privatevoidSomeFunction(){//CompositionContainer是CompositionCont的一个实例ainervarmyExports=CompositionContainer.GetExports();在我的例子中,myExports总是空的在我的CompositionContainer中,我的目录中有一个部分,它有两个ExportDefinitions,它们都具有以下ContractName:“MyNamespace.IMyInterface”。我的导出也正确加载元数据。如果我删除AllowMultiplesetter并仅包含一个导出属性,则myExports变量现在具有单个导出及其加载的元数据。我究竟做错了什么?编辑:如果我使用弱类型元数据,我的出口突然满足:varmyExports=CompositionContainer.GetExports();有任何想法吗?众所周知,MEF在处理AllowMultiple=true时存在一些问题。有关完整解释,您可以查看此处,无论如何它源于元数据保存在Dictionary中的事实,当AllowMultiple为真时,值是数组,并且无法将此类内容映射到IMyInterfaceInfo上。这是我使用的解决方法。首先,您的属性应该派生自属性,而不是ExportAttribute:[MetadataAttribute][AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]一些属性2=一些属性2;一些属性3=一些属性3;}publicTypeSomeProperty1{get;放;}publicdoubleSomeProperty2{get;放;}publicstringSomeProperty3{get;有3个属性,标准导出和自定义属性:[Export(typeof(IMyInterface))][ExportMyInterface(typeof(string),0.1,"whoodata!")][ExportMyInterface(typeof(int),0.4,"asdfasdf!!")]publicclassDecoratedClass:IMyInterface然后您必须为要导入的元数据定义视图。这必须有一个将IDictionary作为参数的构造函数。像这样:publicclassMyInterfaceInfoView{publicIMyInterfaceInfo[]Infos{get;放;}publicMyInterfaceInfoView(IDictionaryaDict){Type[]p1=aDict["SomeProperty1"]asType[];double[]p2=aDict["SomeProperty2"]asdouble[];string[]p3=aDict["SomeProperty3"]asstring[];Infos=newExportMyInterfaceAttribute[p1.Length];for(inti=0;i现在应该可以调用成功了以上是C#学习教程:MEFGetExports使用AllowMultiple=True返回任意内容分享的所有内容如果对大家有用需要了解更多关于C#学习教程,希望大家多多关注---varmyExports=CompositionContainer.GetExports();本文收集自网络,不代表立场,如涉及侵权请点右联系管理员删除,如有转载请注明出处: