C# 如何知道在MEF中作为接口导出的类的原始类型
是否可以使用约定名称通过mef获取导出为接口的类的类型 例如,我想获得MailViewModel类型:C# 如何知道在MEF中作为接口导出的类的原始类型,c#,mef,C#,Mef,是否可以使用约定名称通过mef获取导出为接口的类的类型 例如,我想获得MailViewModel类型: [Export(typeof(IPlugin), "Mail") public class MailViewModel: IPlugin { } 有了MEF,我可以得到一个合同名为“Mail”的Lazy,但我不知道如何得到MailViewModel类型 我需要知道这个类型,因为我“可以”在作为IPlugin导出的类上有一个特定的属性。根据此属性,我将允许或不创建此插件的值(在导航场景中) 当
[Export(typeof(IPlugin), "Mail")
public class MailViewModel: IPlugin { }
有了MEF,我可以得到一个合同名为“Mail”的Lazy,但我不知道如何得到MailViewModel类型
我需要知道这个类型,因为我“可以”在作为IPlugin导出的类上有一个特定的属性。根据此属性,我将允许或不创建此插件的值(在导航场景中)
当我使用[export]以原始类型导出类时,我可以编写以下代码,以了解特定属性是否装饰了我的类:
Attribute.GetCustomAttributes(typeof(myviewmodel), typeof(myattribute));
知道导出的类型和合同名称(IPlugin和“Mail”),我如何知道导出的类是否用特定属性装饰(不实例化它)。这将为您提供具有特定类型和合同名称的导出的所有类型。这是我对这个博客的看法
私有静态IEnumerable GetExportTypes(ComposablePartCatalog目录,类型类型,字符串contractName)
{
返回catalog.Parts.Where(
部分=>
第1部分:定义(
e=>
e、 ContractName==ContractName&&e.Metadata.ContainsKey(“ExportTypeIdentity”)&&
e、 元数据[“ExportTypeIdentity”]。等于(
选择(part=>ReflectionModelServices.GetPartType(part.Value);
}
private static IEnumerable<Type> GetExportTypes(ComposablePartCatalog catalog, Type type, string contractName)
{
return catalog.Parts.Where(
part =>
part.ExportDefinitions.Any(
e =>
e.ContractName == contractName && e.Metadata.ContainsKey("ExportTypeIdentity") &&
e.Metadata["ExportTypeIdentity"].Equals(
type.FullName))).Select(part => ReflectionModelServices.GetPartType(part).Value);
}