简体   繁体   English

这是不好的做法吗? 通用接口的重载方法并返回不同的类型

[英]Is this bad practice? Overloading methods for generic interface and returning different types

As a follow-up to this question: 作为此问题的后续措施:
Is a bad practice to Return different types when overloading a method? 在重载方法时返回不同类型的做法不好吗?

I am thinking about a very simple mapper interface I'm using: 我正在考虑使用一个非常简单的映射器界面:

public interface IMap<T,U>
{
    U MapFrom(T obj);
    T MapFrom(U obj);
}

This is perhaps a more targeted example of the noted question's discussion. 这可能是上述问题讨论的更有针对性的例子。 An instance implementing this interface just maps between types. 实现此接口的实例仅在类型之间映射。
I could do it this way: 我可以这样:

public interface IMap<T,U>
{
    U MapRight(T obj);
    T MapLeft(U obj);
}

but that seems silly because, conceptually, the notion of to and from don't really apply to my generic mapper here. 但似乎愚蠢的,因为,在概念上, 概念并不真正适用于我的通用映射在这里。 It's just a bidirectional map. 这只是一个双向地图。 So, to compliment the linked question: 因此,补充链接的问题:
Is this generic map bad practice? 这是通用地图不好的做法吗?

How should I name methods to avoid returning different types without compromising the "genericness" of the interface? 我应该如何命名方法以避免在不损害接口“通用性”的情况下返回不同类型?

EDIT: Also, in response to an answer, this is for mapper (not that it's really relevant). 编辑:另外,作为对答案的答复,这针对mapper的(不是真的有用)。 I just don't include the mapping method in the interface. 我只是在界面中不包含映射方法。

EDIT2: I suppose the same question would apply if I had a single-direction mapper (or adapter) then I implemented it twice for the two directions... same method name, different return type. EDIT2:如果我有一个单向映射器(或适配器),那么我想同样的问题也会适用,然后我对两个方向实现了两次...相同的方法名称,不同的返回类型。

That's tough because you have no way of restricting T and U to not be the same type, so you always run the risk of having them be the same. 这很困难,因为您无法将T和U限制为不同的类型,因此始终冒着使它们相同的风险。 I'd say you need to just find two names you can live with, like: 我想说的是,您只需要找到两个可以使用的名字即可,例如:

  • MapFirst MapFirst
  • MapSecond 地图第二

Or: 要么:

  • Map 地图
  • ReverseMap 反向映射

Or: 要么:

  • Forward 向前
  • Reverse 相反

First, you're not mapping, you're converting. 首先,您没有映射,而是在转换。 There's a difference. 有区别。 Mapping is what a dictionary does. 映射就是字典的工作。 Converting is what happens when you put in one type and get a different one out. 当您输入一种类型并得到另一种类型时,就会发生转换。

I would create the interface like this: 我将创建这样的界面:

interface IConvertible<TSource, TResult>
{
    TResult Convert(TSource source);
}

You want two way conversion? 您要双向转换吗? Great. 大。 Implement both IConvertible and IConvertible. 实现IConvertible和IConvertible。 Want to encapsulate that into a single interface? 是否要将其封装到单个接口中? Great, create ITwoWayConvertible and implement both. 很好,创建ITwoWayConvertible并实现两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM