重载泛型方法 [英] Overloading generic methods
问题描述
当调用存储对象的一般方法有偶尔需要以不同方式处理特定类型。我知道,你不能超载基础上的限制,但任何其他选择似乎存在其自身的问题。
When calling a generic method for storing an object there are occasionally needs to handle a specific type differently. I know that you can't overload based on constraints, but any other alternative seems to present its own problems.
public bool Save<T>(T entity) where T : class
{ ... some storage logic ... }
我想这样做的是类似如下:
What I would LIKE to do is something like the following:
public bool Save<SpecificClass>(T entity)
{ ... special logic ... }
在过去我们的团队拥有保存这些类如下创建一次性的方法:
In the past our team has created 'one-off' methods for saving these classes as follows:
public bool SaveSpecificClass(SpecificClass sc)
{ ... special logic ... }
不过,如果你不知道该功能的存在,并尝试使用通用(保存),那么你可能碰上了一次性本来是要解决问题的主机。这可以变得更糟,如果一个新的开发走来,看到与普通的问题,并决定他要带的自己的一次性功能。
However, if you don't KNOW that function exists, and you try to use the generic (Save) then you may run into a host of problems that the 'one-off' was supposed to fix. This can be made worse if a new developer comes along, sees the problem with the generic, and decides he's going to fix it with his own one-off function.
所以...
什么是解决这个看似常见的问题?
What are the options for working around this seemingly common issue?
我已经看了,并且使用的UnitOfWork而现在,这似乎是对的只有的实际解决问题的选项 - 但似乎是攻击一只苍蝇用大锤
I've looked at, and used UnitOfWork and right now that seems to be the only option that actually resolves the problem - but seems like attacking a fly with a sledgehammer.
推荐答案
您可以这样做:
public bool Save<T>(T entity) where T : class
{ ... some storage logic ... }
public bool Save(SpecificClass entity)
{ ... special logic ... }
这篇关于重载泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!