Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-向上转换到泛型方法的传递类型_C#_Generics_Casting - Fatal编程技术网

C#-向上转换到泛型方法的传递类型

C#-向上转换到泛型方法的传递类型,c#,generics,casting,C#,Generics,Casting,我正在使用ADO.NET EF和存储库模式。我想分离一些对我的一些实体来说很常见的逻辑,我决定最好的方法是使用泛型方法。这是我的方法声明: internal static void ChangeCode<T>(IService<T> service, Entity entity, MaskedTextBox txtBox, string newCode, long? entityId) where T : Common.DbContextEntit

我正在使用
ADO.NET EF
存储库模式
。我想分离一些对我的一些实体来说很常见的逻辑,我决定最好的方法是使用泛型方法。这是我的方法声明:

internal static void ChangeCode<T>(IService<T> service, Entity entity, MaskedTextBox txtBox, string newCode, long? entityId)
            where T : Common.DbContextEntities.Entity
问题是我只能在
的范围内使用
tempEntity
tempService
如果(entity.GetType()==typeof(Sole))
并且如果我必须检查几个类型(事实上是这样),我必须为每个不同的类型重复所有的业务逻辑。我正在寻找一种在运行时使用specific设置
tempEntity
tempService
的方法,它们可以在方法中的任何地方使用

Sole tempEntity = new Sole();
ISoleService tempService = UnityDependencyResolver.Instance.GetService<ISoleService>();
其中BaseService是所有服务(SoleService等)的父级,包含返回所有服务接口(ISoleService等)的父级IBaseService的虚拟方法

因此,您的所有逻辑都将与BaseService和IBaseService方法一起工作。

Hmm,
IService
就是您正在撰写的父项。但我认为为我想在方法中调用的服务创建另一个接口实际上是一个非常好的主意。谢谢我现在就去试试!
Sole tempEntity = new Sole();
ISoleService tempService = UnityDependencyResolver.Instance.GetService<ISoleService>();
BaseService tempEnitity = (BaseService)Activator.CreateInstance(entity.GetType());
IBaseService tempService = tempEnitity.GetServiceInterface();