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();