C#MEF:导出一种类型的多个对象,并导入特定的对象

Ben*_* K. 3 c# wpf import mef export

我有一个应用程序,它导出同一个类的几个对象,以及只导入特定类的插件.例如

public class Part
{
  string name;
  public Part(string nm)
  {
    name = nm;
  }
}

public class Car //Exports ALL Parts of the Car
{
  [Export(typeof(Part))]
  public Part steeringWheel = new Part("SteeringWheel");

  [Export(typeof(Part))]
  public Part engine = new Part("Engine");

  [Export(typeof(Part))]
  public Part brakes = new Part("Brakes");
}

public class SystemMonitorPlugin //Imports only SOME Parts from the Car
{
  [Import(typeof(Part))]
 public Part engine;

  [Import(typeof(Part))]
  public Part brakes;
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释我是如何实现这种行为的吗?

Ada*_*ney 10

您可以命名导出:

[Export("SteeringWheel", typeof(Part))]
Run Code Online (Sandbox Code Playgroud)

当你想要一个特定的,

[Import("Engine", typeof(Part))]
Run Code Online (Sandbox Code Playgroud)

如果未指定名称,仍可以导入许多类型的零件.