我目前正在建立网络库。我创建了一个名为Packet的类,该类具有一个PacketType枚举,该枚举确定此数据包用于什么目的。
public enum PacketType
{
ConnectionOpen,
KeepAlive,
ConnectionClose
}
public class Packet
{
PacketType packetType;
}
如果用户想添加更多的数据包类型,他该怎么做? 我不想每次创建包时都要设置Packet的PacketType,如下所示:
public class Packet<T>
{
T packetType;
}
有什么想法吗?
答案 0 :(得分:1)
我认为您误解了泛型。您应该阅读一些有关此的内容。 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
在您的情况下,T是一个类而不是一个值。您将描述实现的默认值。您可以使用抽象类来做到这一点:
#region Your Library
public enum PacketType
{
ConnectionOpen,
KeepAlive,
ConnectionClose
}
public abstract class Packet
{
public abstract PacketType PacketType { get; }
}
#endregion
#region Your Implementation
public class MyPacketForKeppAlive : Packet
{
public override PacketType PacketType => PacketType.KeepAlive;
}
public class MyPacketConnectionOpen : Packet
{
public override PacketType PacketType => PacketType.ConnectionOpen;
}
internal static void Main(string[] args)
{
Packet[] packets = new Packet[]
{
new MyPacketForKeppAlive(),
new MyPacketConnectionOpen()
};
foreach (Packet p in packets)
{
Console.WriteLine(p.PacketType);
}
}
#endregion