I am building a series of classes, trying to reduce the manual coding of certain types of classes from the main code.
Whatever way I look, there is always somewhere where manual coding of a particular type of class is required.
I was hoping that I could use the reflection / activator function, etc., to be able to use the work done in the constructor, to be able to return class types (of the desired type) without having to do large ones (although the example here has been shortened) select / switch statement that is in GetPacket .
I know that this is VB.Net, but the project has already been written in this language, I do not mind if you publish examples in C #, I just convert them. But please do not repeat the VB.Net question because it is not about how to do this within the framework.
Imports ProtoBuf Public Class CompatiblePackets Inherits Dictionary(Of Packet.PacketType, Base) Public Sub New() Dim theAssembly As Assembly = Assembly.GetExecutingAssembly For Each t As Type In theAssembly.GetTypes If t.BaseType Is GetType(Base) Then Dim p As Base = CType(t.Assembly.CreateInstance(t.FullName), Base) Me.Add(p.PacketTypeIndicator, p) End If Next End Sub Public Function GetPacket(id As PacketType, data As Stream) As Base Dim activePacket As Base If Me.ContainsKey(id) Then activePacket = Me(id) Else activePacket = Me(PacketType.Generic) End If Try Select Case id Case PacketType.AcknowledgeBulk Return GetPacket(Of AcknowledgeBulk)(activePacket, data) Case PacketType.Generic Return GetPacket(Of Generic)(activePacket, data) Case PacketType.Identification Return GetPacket(Of Identification)(activePacket, data) '''There are so far about 20 more packet types in the real code. Case Else 'unknown type "Computer says No!" End Select Catch ex As Exception If data.GetType Is GetType(MemoryStream) Then Debug.Print(Core.Text.OutputData(CType(data, MemoryStream).ToArray)) End If Throw End Try Debug.Print("Wtf - " & id.ToString()) Return New NoOperation End Function Private Function GetPacket(Of t)(activePacket As Packet.Base, data As Stream) As t Return Serializer.Deserialize(Of t)(data) End Function End Class
source share