【发布时间】:2010-03-02 02:19:12
【问题描述】:
因此,具有相同参数但返回值不同的两个方法将无法编译。在不失去清晰度的情况下定义此接口的最佳方法是什么?
public interface IDuplexChannel<T, U>
{
void Send(T value, int timeout = -1);
void Send(U value, int timeout = -1);
bool TrySend(T value, int timeout = -1);
bool TrySend(U value, int timeout = -1);
T Receive(int timeout = -1);
U Receive(int timeout = -1);
bool TryReceive(out T value, int timeout = -1);
bool TryReceive(out U value, int timeout = -1);
}
我考虑过使用 out 参数,但使用起来会有点尴尬。
public interface IDuplexChannel<T, U>
{
void Send(T value, int timeout = -1);
void Send(U value, int timeout = -1);
bool TrySend(T value, int timeout = -1);
bool TrySend(U value, int timeout = -1);
void Receive(out T value, int timeout = -1);
void Receive(out U value, int timeout = -1);
bool TryReceive(out T value, int timeout = -1);
bool TryReceive(out U value, int timeout = -1);
}
通用版本,有点笨拙但可以。
public interface IDuplexChannel<T, U>
{
void Send(T value, int timeout = -1);
void Send(U value, int timeout = -1);
bool TrySend(T value, int timeout = -1);
bool TrySend(U value, int timeout = -1);
V Receive<V>(int timeout = -1) where V : T, U;
bool TryReceive(out T value, int timeout = -1);
bool TryReceive(out U value, int timeout = -1);
}
【问题讨论】:
-
哪里不编译?错误是什么?
-
如果有人曾经使用过
构造,你会玩得不亦乐乎。 -
@Eric - 回来指出我的愚蠢吧?这是我的代码实验项目中的一个很好的理由。
-
我无意指出任何人的愚蠢。我只是想指出您在使用此界面设计时可能遇到的一个潜在问题。 CLR 对任何类型都有很多问题,这些问题可能会导致泛型构造下的签名统一;在 C# 泛型的原始设计中,即使声明您描述的类型也是非法的。
-
对于这种签名统一导致的特别糟糕的情况,请参阅blogs.msdn.com/ericlippert/archive/2006/04/05/569085.aspx