-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigReader.cs
More file actions
94 lines (80 loc) · 2.71 KB
/
Copy pathConfigReader.cs
File metadata and controls
94 lines (80 loc) · 2.71 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MethodOverloading
{
internal class ConfigReader
{
private readonly Dictionary<string, string> _config;
#pragma warning disable IDE0290 // 使用主构造函数
public ConfigReader(Dictionary<string,string> config) {
_config = config;
}
#pragma warning restore IDE0290 // 使用主构造函数
public string GetValue(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key),$"传入的参数为空。");
}
if (!_config.TryGetValue(key, out var value))
{
throw new DirectoryNotFoundException($"传入的参数:{nameof(key)}不存在");
}
return value;
}
public string GetValue(string key, string defaultValue)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key), $"传入的参数为空。");
}
return _config.TryGetValue(key, out var value) ? value : defaultValue;
}
public T GetValue<T>(string key, T defaultValue = default)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key), $"传入的参数为空。");
}
if (!_config.TryGetValue(key, out var stringValue))
{
return defaultValue;
}
if (string.IsNullOrEmpty(stringValue)) //先检查 null
{
return defaultValue;
}
try
{
// 处理 nullable 类型
var targetType = typeof(T);
if (targetType != null)
{
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = Nullable.GetUnderlyingType(targetType)!;
}
// 类型转换
var converted = Convert.ChangeType(stringValue, targetType);
if (converted is null)
{
return defaultValue;
}
return (T)converted;
}
else
{
throw new Exception();
}
}
catch (Exception)
{
// 转换失败返回默认值
return defaultValue;
}
}
}
}