Cha*_*ion 2 .net c# generics c#-4.0
因为,具有相同参数但返回值不同的两个方法将无法编译.在不失去清晰度的情况下定义此界面的最佳方法是什么?
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);
}
Run Code Online (Sandbox Code Playgroud)
我考虑使用params,但这会使它使用起来有点尴尬.
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);
}
Run Code Online (Sandbox Code Playgroud)
通用版本,有点笨拙,但它的工作原理.
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);
}
Run Code Online (Sandbox Code Playgroud)
主要问题是您尝试同时从两端查看双工通道.数据在双工通道上双向传播,但仍有明确的终点.你在一端发送的是你在另一端收到的.
public interface IDuplexChannel<TSend, TReceive>
{
void Send(TSend data);
TReceive Receive();
}
Run Code Online (Sandbox Code Playgroud)
"PERSON" A "PERSON" B
O int -----------------> O
-|- <-------------- string -|-
/ \ / \
IDuplexChannel<int, string> IDuplexChannel<string, int>
Run Code Online (Sandbox Code Playgroud)