【问题标题】:Cast Interface in generic method泛型方法中的转换接口
【发布时间】:2010-12-20 06:42:28
【问题描述】:
我是界面的新用户。我的问题是我创建了一个有两个参数的通用类
一个是对象类型,另一个是接口类型。现在在类中我可以使用反射来投射对象,但我没有得到投射接口的方法。
【问题讨论】:
标签:
c#
reflection
interface
generics
【解决方案1】:
你在寻找类似的东西
public class Factory<TClass, TInterface> where TClass : TInterface, new()
{
public TInterface Create()
{
return new TClass();
}
}
'where TClass : TInterface, new()' 是建立 TClass 和 TInterface 之间关系的部分。如果您省略 TInterface,那么您将无法投射到该接口。
然后可以像这样调用
var factory = new Factory<MySuperService, IService>();
IService service = factory.Create();
如果这不能解决您的问题,请提供代码来说明问题。