alielie
7 天以前 e57938fbda9bff702004038f76d009422968bff5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using DeviceService.Core;
using System.Reflection;
using System.Windows.Controls;
 
namespace DeviceService
{
    /// <summary>
    /// 按命名规则创建设备配置控件:设备类名 CanDevice 对应 CanDeviceConfigControl。
    /// </summary>
    public static class DeviceConfigControlFactory
    {
        public static UserControl? Create(IDevice device)
        {
            if (device == null) throw new ArgumentNullException(nameof(device));
 
            string controlName = device.GetType().Name + "ConfigControl";
 
            try
            {
                Type? type = typeof(DeviceConfigControlFactory).Assembly.GetTypes()
                    .FirstOrDefault(t => t.Name == controlName
                                         && typeof(UserControl).IsAssignableFrom(t)
                                         && !t.IsAbstract);
 
                return type == null ? null : (UserControl?)Activator.CreateInstance(type);
            }
            catch (ReflectionTypeLoadException ex)
            {
                Type? type = ex.Types.FirstOrDefault(t => t?.Name == controlName
                                                          && typeof(UserControl).IsAssignableFrom(t)
                                                          && !t.IsAbstract);
                return type == null ? null : (UserControl?)Activator.CreateInstance(type);
            }
        }
    }
}