我想通过 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/