c# - 在 MEF 中导出泛型

标签 c# generics c#-4.0 dependency-injection mef

我想通过 MEF 将通用类导出到通用接口(interface)。我的目标是:

public interface IService<T> { }

[Export(typeof(IService<T>))] // error!!!!!!
public class Service<T> { }

public class Client<T> {
    [Import]
    private IService<T> _service;
}

但是当我尝试导出 IService<T> ,我得到这个错误:

Attribute argument cannot use type parameters

有人可以指导我这样做吗?

最佳答案

尝试

[Export(typeof(IService<>))]

要从 typeof 运算符获得泛型类型定义,您可以省略类型参数。对于具有多个类型参数的类型,使用逗号来指示类型的“元数”。例如:

typeof(List<>)              // not: typeof(List<T>)
typeof(IDictionary<,>)      // not: typeof(IDictionary<K, V>)

关于c# - 在 MEF 中导出泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9295310/

相关文章:

c# - 使用未分配的局部变量

c - 我收到错误 : petition of a member in something that it's not an structure or an enum in C

.net - System.Net.Caching.HttpRequestCachePolicy 和 CloudBlob.FetchAttributes 之间的冲突

c# - Action<T> 等效于属性

c# - List<T> 线程安全

c# - 仅排除特定平台上的单元测试

c# - NHibernate 中无法识别的配置部分 applicationSettings

c# - 执行 exe 时出现未知发布者错误

c# - 如何使用反射调用泛型类型内的非泛型方法

swift - 字典作为数组的通用元素