是否可以创建一个需要通用类型的方法,然后返回类型基于给定类型的成员
像这样的东西
class ExampleClass
{
public T.ReturnType Send<T>() where T : ClassWithType
{
...
}
}
abstract class ClassWithType
{
internal abstract Type ReturnType { get; }
}
如果不可能会有什么好的选择。
提前致谢
答案 0 :(得分:2)
因为它评论你说你想通过套接字发送一个数据包,每个数据包有不同的返回类型 - 你可以在数据包类本身编码返回类型:
public abstract class Packet<TResponse> {
// other members here
public abstract TResponse DecodeResponse(byte[] raw);
}
public class IntPacket : Packet<int> {
public override int DecodeResponse(byte[] raw) {
// decode
return 0;
}
}
然后您的发送方法变为:
static TResponse Send<TResponse>(Packet<TResponse> packet) {
// send, got response
byte[] raw = GetResponse();
return packet.DecodeResponse(raw);
}
呼叫变为公正:
int response = Send(new IntPacket());