在泛型方法铸造界面 [英] Cast Interface in generic method

查看:145
本文介绍了在泛型方法铸造界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好所有
我界面的新用户。我的问题是我必须创建一个有两个参数
一个泛型类是对象类型另一个是接口类型。现在类中,我可以使用反射投对象,但我没有得到施展接口的方式。

Hello All I am new user of interface. My problem is i have create a Generic class which have two parameter one is object type another is interface type. Now within class i can cast object using Reflection but i am not getting the way to cast interface.

推荐答案

您寻找类似

public class Factory<TClass, TInterface> where TClass : TInterface, new()
{
    public TInterface Create()
    {
        return new TClass();
    }
}



阿凡TClass:TInterface,新的()就是TClass和TInterface之间的关系是建立在一部分。如果你离开了TInterface,那么你将无法转换到该接口。

The 'where TClass : TInterface, new()' is the part where the relation between TClass and TInterface is set up. If you leave out TInterface then you will be unable to cast to the interface.

然后可以调用像

var factory = new Factory<MySuperService, IService>();
IService service = factory.Create();

请提供代码来说明问题,如果这不能解决你的问题。

Please supply code to illustrate the problem if this does not solve your problem.

这篇关于在泛型方法铸造界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆