MEF 使用字符串获取导出
MEF getting exports with a string
是否可以仅通过字符串获取导出?这些部件在容器中,但我只有一个字符串来解析正确的部件。 MEF 似乎想要解析类型,而 Type.GetType() 之类的东西需要硬引用。不能使用通用接口,需要非常具体的部分。
可以更改字符串以匹配任何需要的内容。 (我认为)
container.GetExports("ClassLibrary1.Class1")
我没有玩过元数据,但你能根据元数据字符串解析吗?
谢谢
如果您尝试在不参考类型的情况下获取零件,那么您希望在获得该零件后完成什么?另请注意,您可以使用 typeof
或使用泛型方法来引用没有对象的类型。
这就是 MEF 通常使用 public 接口而不是具体的 and/or 非 public 类型连接的原因。
您正在寻找的是给定类型的默认合同名称,但是查找该默认名称的任何辅助方法都需要 Type
对象,并且属于与上述相同的解释。
编辑:如果您要查找给定 class 的合同名称,则以上内容适用。同类出口的区分,见下文
导出的时候可以specify both a contract name and export type,比如
[Export("Contract", typeof(IInterface))]
public class Part : IInterface { /*...*/ }
这可以让您区分多个部分。如果您希望将零件作为 ImportMany
指令的一部分导入,则必须 还 导出它时不带合同名称,例如
[Export("Contract", typeof(IInterface))]
[Export(typeof(IInterface))]
public class Part : IInterface { /*...*/ }
由于允许属性取 const
值,因此在名称集合中指定单个合同名称可能也很有用,IE
public static class ContractNames
{
public const string Contract = "Contract";
}
[Export(ContractNames.Contract, typeof(IInterface))]
[Export(typeof(IInterface))]
public class Part : IInterface { /*...*/ }
...
container.GetExportedValue<IInterface>(ContractNames.Contract);
注意上面使用 GetExportedValue
而不是 GetExports
因为前者将直接组合 return 值,而不是导出元数据
是否可以仅通过字符串获取导出?这些部件在容器中,但我只有一个字符串来解析正确的部件。 MEF 似乎想要解析类型,而 Type.GetType() 之类的东西需要硬引用。不能使用通用接口,需要非常具体的部分。
可以更改字符串以匹配任何需要的内容。 (我认为)
container.GetExports("ClassLibrary1.Class1")
我没有玩过元数据,但你能根据元数据字符串解析吗?
谢谢
如果您尝试在不参考类型的情况下获取零件,那么您希望在获得该零件后完成什么?另请注意,您可以使用 typeof
或使用泛型方法来引用没有对象的类型。
这就是 MEF 通常使用 public 接口而不是具体的 and/or 非 public 类型连接的原因。
您正在寻找的是给定类型的默认合同名称,但是查找该默认名称的任何辅助方法都需要 Type
对象,并且属于与上述相同的解释。
编辑:如果您要查找给定 class 的合同名称,则以上内容适用。同类出口的区分,见下文
导出的时候可以specify both a contract name and export type,比如
[Export("Contract", typeof(IInterface))]
public class Part : IInterface { /*...*/ }
这可以让您区分多个部分。如果您希望将零件作为 ImportMany
指令的一部分导入,则必须 还 导出它时不带合同名称,例如
[Export("Contract", typeof(IInterface))]
[Export(typeof(IInterface))]
public class Part : IInterface { /*...*/ }
由于允许属性取 const
值,因此在名称集合中指定单个合同名称可能也很有用,IE
public static class ContractNames
{
public const string Contract = "Contract";
}
[Export(ContractNames.Contract, typeof(IInterface))]
[Export(typeof(IInterface))]
public class Part : IInterface { /*...*/ }
...
container.GetExportedValue<IInterface>(ContractNames.Contract);
注意上面使用 GetExportedValue
而不是 GetExports
因为前者将直接组合 return 值,而不是导出元数据