From 342a30bc7cbfdf587721b320ebda226ec2a1f91e Mon Sep 17 00:00:00 2001 From: yedajiang44 <602830483@qq.com> Date: Sun, 14 May 2023 01:24:10 +0800 Subject: [PATCH] review --- .../Internal/JT808_0x8900_Custom_Factory.cs | 54 ++++++++++++------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/src/JT808.Protocol/Internal/JT808_0x8900_Custom_Factory.cs b/src/JT808.Protocol/Internal/JT808_0x8900_Custom_Factory.cs index f1011ef..a2a9a2c 100644 --- a/src/JT808.Protocol/Internal/JT808_0x8900_Custom_Factory.cs +++ b/src/JT808.Protocol/Internal/JT808_0x8900_Custom_Factory.cs @@ -15,35 +15,53 @@ namespace JT808.Protocol.Internal public void Register(Assembly externalAssembly) { - foreach (var type in externalAssembly.GetTypes().Where(w => w.GetInterface(nameof(JT808_0x8900_BodyBase)) == typeof(JT808_0x8900_BodyBase))) + foreach (var item in externalAssembly.GetTypes().Where(x => x.GetConstructor(Type.EmptyTypes) != default)) { - var instance = Activator.CreateInstance(type); - var attachid = (byte)type.GetProperty(nameof(JT808_0x0200_CustomBodyBase.AttachInfoId)).GetValue(instance); - if (Map.ContainsKey(attachid)) - { - throw new ArgumentException($"{type.FullName} {attachid} An element with the same key already exists."); - } - else - { - Map.Add(attachid, instance); - } + Register(item); } } - public IJT808_0x8900_Custom_Factory SetMap() where TJT808_0x8900_Custom_Factory : JT808_0x8900_BodyBase + public IJT808_0x8900_Custom_Factory SetMap() { - Type type = typeof(TJT808_0x8900_Custom_Factory); - var instance = Activator.CreateInstance(type); - var passthroughType = (byte)type.GetProperty(nameof(JT808_0x8900_BodyBase.PassthroughType)).GetValue(instance); - if (Map.ContainsKey(passthroughType)) + var type = typeof(T); + if (type.GetConstructor(Type.EmptyTypes) != default) { - throw new ArgumentException($"{type.FullName} {passthroughType} An element with the same key already exists."); + Register(type); } else { - Map.Add(passthroughType, instance); + throw new ArgumentException($"{type.FullName} must be parameterless constructor."); } return this; } + + void Register(Type type) + { + var instance = Activator.CreateInstance(type); + if (instance is JT808_0x0200_CustomBodyBase jT808_0X0200_Custom) + { + var key = jT808_0X0200_Custom.AttachInfoId; + if (Map.ContainsKey(key)) + { + throw new ArgumentException($"{type.FullName} {key} An element with the same key already exists."); + } + else + { + Map.Add(key, instance); + } + } + else if (instance is JT808_0x8900_BodyBase jT808_0X8900_Custom) + { + var key = jT808_0X8900_Custom.PassthroughType; + if (Map.ContainsKey(key)) + { + throw new ArgumentException($"{type.FullName} {key} An element with the same key already exists."); + } + else + { + Map.Add(key, instance); + } + } + } } }