XFEExtension
【DLL】XFE各类拓展是一个C#的DLL库,旨在优化C#代码中常用语句的使用,并提供更简洁的访问方式,同时提供Xunit测试框架,快速搭建服务器/客户端,免费ChatGPTAPI接口,免费通讯服务器,XFE下载器,新增格式等
关注
0
Fork
0
Star
0
返回提交历史
Modified
XFEExtension.NetCore/AttributeExtension/AttributeExtension.cs
+32
-142
Modified
XFEExtension.NetCore/BufferExtension/BufferExtension.cs
+21
-33
Modified
XFEExtension.NetCore/FileExtension/FileExtension.cs
+103
-125
Modified
XFEExtension.NetCore/ObjectExtension/ObjectExtension.cs
+17
-54
Modified
XFEExtension.NetCore/ReflectionExtension/ReflectionExtension.cs
+13
-14
Modified
XFEExtension.NetCore/StringExtension/StringExtension.cs
+62
-61
Modified
XFEExtension.NetCore/TaskExtension/TaskExtension.cs
+1
-1
Modified
XFEExtension.NetCore/XFEExtension/XFECode.cs
+2
-2
XFEstudio/XFEExtension
完善部分语句
01a0bd3
代码差异
8 个文件
+251
-432
@@ -19,21 +19,11 @@ public static class AttributeExtension
19
19
{
20
20
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
21
21
if (type is null)
22
{
23
22
throw new XFEExtensionException($"未找到类{className}");
24
}
25
else
26
{
27
var method = type.GetMethod(methodName);
28
if (method is null)
29
{
30
throw new XFEExtensionException($"未找到方法{methodName}");
31
}
32
else
33
{
34
return method.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
35
}
36
}
23
var method = type.GetMethod(methodName);
24
if (method is null)
25
throw new XFEExtensionException($"未找到方法{methodName}");
26
return method.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
37
27
}
38
28
/// <summary>
39
29
/// 获取给定类的某个方法的给定属性的对象列表
@@ -46,21 +36,9 @@ public static class AttributeExtension
46
36
{
47
37
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
48
38
if (type is null)
49
{
50
39
throw new XFEExtensionException($"未找到类{className}");
51
}
52
else
53
{
54
var method = type.GetMethod(methodName);
55
if (method is null)
56
{
57
throw new XFEExtensionException($"未找到方法{methodName}");
58
}
59
else
60
{
61
return method.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
62
}
63
}
40
var method = type.GetMethod(methodName);
41
return method is null ? throw new XFEExtensionException($"未找到方法{methodName}") : method.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
64
42
}
65
43
/// <summary>
66
44
/// 获取给定类的某个字段的给定属性的对象
@@ -73,21 +51,11 @@ public static class AttributeExtension
73
51
{
74
52
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
75
53
if (type is null)
76
{
77
54
throw new XFEExtensionException($"未找到类{className}");
78
}
79
else
80
{
81
var field = type.GetField(fieldName);
82
if (field is null)
83
{
84
throw new XFEExtensionException($"未找到字段{fieldName}");
85
}
86
else
87
{
88
return field.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
89
}
90
}
55
var field = type.GetField(fieldName);
56
if (field is null)
57
throw new XFEExtensionException($"未找到字段{fieldName}");
58
return field.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
91
59
}
92
60
/// <summary>
93
61
/// 获取给定类的某个字段的给定属性的对象列表
@@ -100,21 +68,9 @@ public static class AttributeExtension
100
68
{
101
69
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
102
70
if (type is null)
103
{
104
71
throw new XFEExtensionException($"未找到类{className}");
105
}
106
else
107
{
108
var field = type.GetField(fieldName);
109
if (field is null)
110
{
111
throw new XFEExtensionException($"未找到字段{fieldName}");
112
}
113
else
114
{
115
return field.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
116
}
117
}
72
var field = type.GetField(fieldName);
73
return field is null ? throw new XFEExtensionException($"未找到字段{fieldName}") : field.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
118
74
}
119
75
/// <summary>
120
76
/// 获取给定类的某个属性的给定属性的对象
@@ -127,21 +83,11 @@ public static class AttributeExtension
127
83
{
128
84
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
129
85
if (type is null)
130
{
131
86
throw new XFEExtensionException($"未找到类{className}");
132
}
133
else
134
{
135
var property = type.GetProperty(propertyName);
136
if (property is null)
137
{
138
throw new XFEExtensionException($"未找到属性{propertyName}");
139
}
140
else
141
{
142
return property.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
143
}
144
}
87
var property = type.GetProperty(propertyName);
88
if (property is null)
89
throw new XFEExtensionException($"未找到属性{propertyName}");
90
return property.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
145
91
}
146
92
/// <summary>
147
93
/// 获取给定类的某个属性的给定属性的对象列表
@@ -154,21 +100,9 @@ public static class AttributeExtension
154
100
{
155
101
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
156
102
if (type is null)
157
{
158
103
throw new XFEExtensionException($"未找到类{className}");
159
}
160
else
161
{
162
var property = type.GetProperty(propertyName);
163
if (property is null)
164
{
165
throw new XFEExtensionException($"未找到属性{propertyName}");
166
}
167
else
168
{
169
return property.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
170
}
171
}
104
var property = type.GetProperty(propertyName);
105
return property is null ? throw new XFEExtensionException($"未找到属性{propertyName}") : property.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
172
106
}
173
107
/// <summary>
174
108
/// 获取给定类的给定方法的给定参数的给定属性的对象
@@ -182,29 +116,14 @@ public static class AttributeExtension
182
116
{
183
117
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
184
118
if (type is null)
185
{
186
119
throw new XFEExtensionException($"未找到类{className}");
187
}
188
else
189
{
190
var method = type.GetMethod(methodName);
191
if (method is null)
192
{
193
throw new XFEExtensionException($"未找到方法{methodName}");
194
}
195
else
196
{
197
var param = method.GetParameters().FirstOrDefault(x => x.Name == paramName);
198
if (param is null)
199
{
200
throw new XFEExtensionException($"未找到参数{paramName}");
201
}
202
else
203
{
204
return param.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
205
}
206
}
207
}
120
var method = type.GetMethod(methodName);
121
if (method is null)
122
throw new XFEExtensionException($"未找到方法{methodName}");
123
var param = method.GetParameters().FirstOrDefault(x => x.Name == paramName);
124
if (param is null)
125
throw new XFEExtensionException($"未找到参数{paramName}");
126
return param.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
208
127
}
209
128
/// <summary>
210
129
/// 获取给定类的给定方法的给定参数的给定属性的对象列表
@@ -218,29 +137,12 @@ public static class AttributeExtension
218
137
{
219
138
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
220
139
if (type is null)
221
{
222
140
throw new XFEExtensionException($"未找到类{className}");
223
}
224
else
225
{
226
var method = type.GetMethod(methodName);
227
if (method is null)
228
{
229
throw new XFEExtensionException($"未找到方法{methodName}");
230
}
231
else
232
{
233
var param = method.GetParameters().FirstOrDefault(x => x.Name == paramName);
234
if (param is null)
235
{
236
throw new XFEExtensionException($"未找到参数{paramName}");
237
}
238
else
239
{
240
return param.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
241
}
242
}
243
}
141
var method = type.GetMethod(methodName);
142
if (method is null)
143
throw new XFEExtensionException($"未找到方法{methodName}");
144
var param = method.GetParameters().FirstOrDefault(x => x.Name == paramName);
145
return param is null ? throw new XFEExtensionException($"未找到参数{paramName}") : param.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
244
146
}
245
147
/// <summary>
246
148
/// 给定类的给定属性的对象
@@ -252,13 +154,8 @@ public static class AttributeExtension
252
154
{
253
155
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
254
156
if (type is null)
255
{
256
157
throw new XFEExtensionException($"未找到类{className}");
257
}
258
else
259
{
260
return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
261
}
158
return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
262
159
}
263
160
/// <summary>
264
161
/// 给定类的给定属性的对象列表
@@ -269,14 +166,7 @@ public static class AttributeExtension
269
166
public static List<T?> GetAttributesOnClass<T>(string className) where T : Attribute
270
167
{
271
168
var type = Assembly.GetCallingAssembly().GetType(className, false, true);
272
if (type is null)
273
{
274
throw new XFEExtensionException($"未找到类{className}");
275
}
276
else
277
{
278
return type.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
279
}
169
return type is null ? throw new XFEExtensionException($"未找到类{className}") : type.GetCustomAttributes(typeof(T), false).Select(x => x as T).ToList();
280
170
}
281
171
#endregion
282
172
#region 拓展方法
@@ -8,7 +8,7 @@ namespace XFEExtension.NetCore.BufferExtension;
8
8
public static class BufferExtension
9
9
{
10
10
/// <param name="buffer"></param>
11
extension(byte[] buffer)
11
extension(byte[]? buffer)
12
12
{
13
13
/// <summary>
14
14
/// 获取第一个匹配Buffer的位置
@@ -18,6 +18,9 @@ public static class BufferExtension
18
18
public int IndexOf(byte[] targetBuffer)
19
19
{
20
20
int index = -1;
21
if (buffer is null)
22
return index;
23
21
24
for (int i = 0; i < buffer.Length; i++)
22
25
{
23
26
if (buffer[i] != targetBuffer[0])
@@ -30,6 +33,7 @@ public static class BufferExtension
30
33
isMatch = false;
31
34
break;
32
35
}
36
33
37
if (!isMatch)
34
38
continue;
35
39
index = i;
@@ -47,6 +51,9 @@ public static class BufferExtension
47
51
public int[] IndexesOf(byte[] targetBuffer, bool shareable = false)
48
52
{
49
53
var indexes = new List<int>();
54
if (buffer == null)
55
return [.. indexes];
56
50
57
for (int i = 0; i < buffer.Length; i++)
51
58
{
52
59
if (buffer[i] != targetBuffer[0])
@@ -57,6 +64,7 @@ public static class BufferExtension
57
64
if (!shareable)
58
65
i += targetBuffer.Length - 1;
59
66
}
67
60
68
return [.. indexes];
61
69
}
62
70
@@ -69,24 +77,19 @@ public static class BufferExtension
69
77
public byte[] Replace(byte[] originBuffer, byte[] targetBuffer)
70
78
{
71
79
if (originBuffer is null || originBuffer.LongLength == 0)
72
{
73
80
throw new ArgumentException("Origin buffer cannot be null or empty.");
74
}
75
81
if (buffer is null || buffer.LongLength == 0)
76
{
77
82
return [];
78
}
79
83
List<byte> result = [];
80
84
for (long i = 0; i <= buffer.LongLength - originBuffer.LongLength; i++)
81
85
{
82
86
bool isMatch = true;
83
87
for (long j = 0; j < originBuffer.LongLength; j++)
84
88
{
85
if (buffer[i + j] != originBuffer[j])
86
{
87
isMatch = false;
88
break;
89
}
89
if (buffer[i + j] == originBuffer[j])
90
continue;
91
isMatch = false;
92
break;
90
93
}
91
94
if (isMatch)
92
95
{
@@ -120,17 +123,17 @@ public static class BufferExtension
120
123
{
121
124
var newBuffer = new byte[indexes[i] - index];
122
125
for (long j = index; j < indexes[i]; j++)
123
{
124
newBuffer[j - index] = buffer[j];
125
}
126
if (buffer is not null)
127
newBuffer[j - index] = buffer[j];
126
128
buffers.Add(newBuffer);
127
129
index = indexes[i] + targetBuffer.LongLength;
128
130
}
131
132
if (buffer is null)
133
return buffers;
129
134
var lastBuffer = new byte[buffer.LongLength - index];
130
135
for (long i = index; i < buffer.LongLength; i++)
131
{
132
136
lastBuffer[i - index] = buffer[i];
133
}
134
137
buffers.Add(lastBuffer);
135
138
return buffers;
136
139
}
@@ -163,11 +166,7 @@ public static class BufferExtension
163
166
/// <returns></returns>
164
167
public byte[] AddHeaderAndPack(params string[] headers)
165
168
{
166
var buffers = new List<byte[]>();
167
foreach (var header in headers)
168
{
169
buffers.Add(Encoding.UTF8.GetBytes(header));
170
}
169
var buffers = headers.Select(header => Encoding.UTF8.GetBytes(header)).ToList();
171
170
buffers.Add(buffer);
172
171
return buffers.PackBuffer();
173
172
}
@@ -177,23 +176,12 @@ public static class BufferExtension
177
176
/// </summary>
178
177
/// <param name="headers"></param>
179
178
/// <returns></returns>
180
public byte[] AddHeaderAndPack(params byte[] headers)
181
{
182
return new List<byte[]>() { headers, buffer }.PackBuffer();
183
}
179
public byte[] AddHeaderAndPack(params byte[] headers) => new List<byte[]>() { headers, buffer }.PackBuffer();
184
180
185
181
/// <summary>
186
182
/// 将XEFBuffer转换为BufferList
187
183
/// </summary>
188
184
/// <returns></returns>
189
public List<byte[]> UnPackBuffer()
190
{
191
var unPackedBuffers = new List<byte[]>();
192
foreach (var unPackedBuffer in buffer.Split([0x01, 0x02, 0x03]))
193
{
194
unPackedBuffers.Add(unPackedBuffer.Replace([0x02, 0x02, 0x03], [0x02, 0x03]));
195
}
196
return unPackedBuffers;
197
}
185
public List<byte[]> UnPackBuffer() => buffer.Split([0x01, 0x02, 0x03]).Select(unPackedBuffer => unPackedBuffer.Replace([0x02, 0x02, 0x03], [0x02, 0x03])).ToList();
198
186
}
199
187
}
@@ -9,19 +9,6 @@ namespace XFEExtension.NetCore.FileExtension;
9
9
/// </summary>
10
10
public static class FileExtension
11
11
{
12
/// <summary>
13
/// 将字符串写入文件
14
/// </summary>
15
/// <param name="text"></param>
16
/// <param name="fileName">目标文件路径及文件名</param>
17
public static void WriteIn(this string text, string fileName)
18
{
19
FileInfo fileInfo = new(fileName);
20
using var fileStream = fileInfo.Create();
21
var stream = Encoding.UTF8.GetBytes(text);
22
fileStream.Write(stream, 0, stream.Length);
23
fileStream.Flush();
24
}
25
12
/// <summary>
26
13
/// 将非法字符串写入文件
27
14
/// </summary>
@@ -56,31 +43,23 @@ public static class FileExtension
56
43
streamReader.Close();
57
44
return true;
58
45
}
59
else
60
{
61
content = string.Empty;
62
return false;
63
}
46
content = string.Empty;
47
return false;
64
48
}
65
49
66
50
/// <summary>
67
51
/// 读取文件中的字符串
68
52
/// </summary>
69
53
/// <returns>目标文件内容,如不存在则返回-1</returns>
70
public string? ReadOut()
54
public string ReadOut()
71
55
{
72
56
FileInfo fileInfo = new(name);
73
if (fileInfo.Exists)
74
{
75
using var streamReader = fileInfo.OpenText();
76
var text = streamReader.ReadToEnd();
77
streamReader.Close();
78
return text;
79
}
80
else
81
{
57
if (!fileInfo.Exists)
82
58
return "-1";
83
}
59
using var streamReader = fileInfo.OpenText();
60
var text = streamReader.ReadToEnd();
61
streamReader.Close();
62
return text;
84
63
}
85
64
86
65
/// <summary>
@@ -89,20 +68,95 @@ public static class FileExtension
89
68
/// <returns></returns>
90
69
[Obsolete("序列化方法在.NET 8.0中已经不再受支持")]
91
70
public T? ReadOutObj<T>()
71
{
72
var fileInfo = new FileInfo(name);
73
if (!fileInfo.Exists)
74
return default;
75
using var fileStream = fileInfo.OpenRead();
76
BinaryFormatter bf = new();
77
var result = (T)bf.Deserialize(fileStream);
78
fileStream.Close();
79
return result;
80
}
81
82
/// <summary>
83
/// 将字符串写入文件
84
/// </summary>
85
/// <param name="fileName">目标文件路径及文件名</param>
86
public void WriteIn(string fileName)
87
{
88
FileInfo fileInfo = new(fileName);
89
using var fileStream = fileInfo.Create();
90
var stream = Encoding.UTF8.GetBytes(name);
91
fileStream.Write(stream, 0, stream.Length);
92
fileStream.Flush();
93
}
94
95
/// <summary>
96
/// 读取文件中的字符串
97
/// </summary>
98
/// <param name="exist">是否存在</param>
99
/// <returns></returns>
100
[Obsolete("序列化方法在.NET 8.0中已经不再受支持")]
101
public string? ReadOutObj(out bool exist)
92
102
{
93
103
FileInfo fileInfo = new(name);
94
if (fileInfo.Exists)
104
exist = fileInfo.Exists;
105
if (!fileInfo.Exists)
106
return "-1";
107
using var fileStream = fileInfo.OpenRead();
108
BinaryFormatter binaryFormatter = new();
109
var text = binaryFormatter.Deserialize(fileStream).ToString();
110
fileStream.Close();
111
return text;
112
}
113
114
/// <summary>
115
/// 从文件反序列化对象
116
/// </summary>
117
/// <typeparam name="T">类型</typeparam>
118
/// <returns></returns>
119
[Obsolete("序列化方法在.NET 8.0中已经不再受支持")]
120
public T DeserializeFromFile<T>()
121
{
122
BinaryFormatter readBinary = new();
123
using var readStream = File.OpenRead(name);
124
T obj = (T)readBinary.Deserialize(readStream);
125
readStream.Close();
126
return obj;
127
}
128
129
/// <summary>
130
/// 获取占用某个文件的程序
131
/// </summary>
132
/// <returns></returns>
133
public Process? GetOwningProcess()
134
{
135
try
95
136
{
96
using var fileStream = fileInfo.OpenRead();
97
BinaryFormatter bf = new();
98
var result = (T)bf.Deserialize(fileStream);
99
fileStream.Close();
100
return result;
137
// 获取所有正在运行的进程
138
Process[] processes = Process.GetProcesses();
139
140
foreach (Process process in processes)
141
{
142
try
143
{
144
// 获取进程打开的文件句柄信息
145
if (process.Modules.Cast<ProcessModule>().Any(module =>
146
module.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)))
147
return process; // 返回占用文件的进程
148
}
149
catch (Exception)
150
{
151
// 忽略无法访问的进程
152
}
153
}
101
154
}
102
else
155
catch (Exception)
103
156
{
104
return default;
157
// 忽略获取进程信息时的异常
105
158
}
159
return null; // 如果没有找到占用文件的进程,返回null
106
160
}
107
161
}
108
162
@@ -116,42 +170,14 @@ public static class FileExtension
116
170
{
117
171
FileInfo fileInfo = new(fileName);
118
172
exist = fileInfo.Exists;
119
if (fileInfo.Exists)
120
{
121
using StreamReader streamReader = fileInfo.OpenText();
122
var text = streamReader.ReadLine();
123
streamReader.Close();
124
return text;
125
}
126
else
127
{
128
return "-1";
129
}
130
}
131
/// <summary>
132
/// 读取文件中的字符串
133
/// </summary>
134
/// <param name="fileName"></param>
135
/// <param name="exist">是否存在</param>
136
/// <returns></returns>
137
[Obsolete("序列化方法在.NET 8.0中已经不再受支持")]
138
public static string? ReadOutObj(this string fileName, out bool exist)
139
{
140
FileInfo fileInfo = new(fileName);
141
exist = fileInfo.Exists;
142
if (fileInfo.Exists)
143
{
144
using var fileStream = fileInfo.OpenRead();
145
BinaryFormatter binaryFormatter = new();
146
var text = binaryFormatter.Deserialize(fileStream).ToString();
147
fileStream.Close();
148
return text;
149
}
150
else
151
{
173
if (!fileInfo.Exists)
152
174
return "-1";
153
}
175
using StreamReader streamReader = fileInfo.OpenText();
176
var text = streamReader.ReadLine();
177
streamReader.Close();
178
return text;
154
179
}
180
155
181
/// <summary>
156
182
/// 序列化对象到文件
157
183
/// </summary>
@@ -161,26 +187,12 @@ public static class FileExtension
161
187
public static void SerializeToFile(this object obj, string fileName)
162
188
{
163
189
BinaryFormatter writeBinary = new();
164
using var WriteStream = File.OpenWrite(fileName);
165
writeBinary.Serialize(WriteStream, obj);
166
WriteStream.Flush();
167
WriteStream.Close();
168
}
169
/// <summary>
170
/// 从文件反序列化对象
171
/// </summary>
172
/// <typeparam name="T">类型</typeparam>
173
/// <param name="fileName"></param>
174
/// <returns></returns>
175
[Obsolete("序列化方法在.NET 8.0中已经不再受支持")]
176
public static T DeserializeFromFile<T>(this string fileName)
177
{
178
BinaryFormatter readBinary = new();
179
using var readStream = File.OpenRead(fileName);
180
T obj = (T)readBinary.Deserialize(readStream);
181
readStream.Close();
182
return obj;
190
using var writeStream = File.OpenWrite(fileName);
191
writeBinary.Serialize(writeStream, obj);
192
writeStream.Flush();
193
writeStream.Close();
183
194
}
195
184
196
/// <summary>
185
197
/// 输出文件大小
186
198
/// </summary>
@@ -196,41 +208,7 @@ public static class FileExtension
196
208
order++;
197
209
len /= 1024;
198
210
}
199
return string.Format("{0:0.##} {1}", len, sizes[order]);
200
}
201
/// <summary>
202
/// 获取占用某个文件的程序
203
/// </summary>
204
/// <param name="filePath">文件路径</param>
205
/// <returns></returns>
206
public static Process? GetOwningProcess(this string filePath)
207
{
208
try
209
{
210
// 获取所有正在运行的进程
211
Process[] processes = Process.GetProcesses();
212
213
foreach (Process process in processes)
214
{
215
try
216
{
217
// 获取进程打开的文件句柄信息
218
foreach (ProcessModule module in process.Modules)
219
{
220
if (module.FileName.Equals(filePath, StringComparison.OrdinalIgnoreCase))
221
{
222
return process; // 返回占用文件的进程
223
}
224
}
225
}
226
catch (Exception)
227
{
228
// 忽略无法访问的进程
229
}
230
}
231
}
232
catch { }
233
return null; // 如果没有找到占用文件的进程,返回null
211
return $"{len:0.##} {sizes[order]}";
234
212
}
235
213
236
214
/// <param name="fileStream">文件流</param>
@@ -7,19 +7,14 @@ public static class ObjectExtension
7
7
{
8
8
/// <param name="source"></param>
9
9
/// <typeparam name="T"></typeparam>
10
extension<T>(T source) where T : class
10
extension<T>(T? source) where T : class
11
11
{
12
12
/// <summary>
13
13
/// 进行浅拷贝
14
14
/// </summary>
15
15
/// <returns>浅拷贝后的对象</returns>
16
16
/// <exception cref="ArgumentNullException">无类型错误</exception>
17
public T ActiveCopyOf()
18
{
19
return source is null
20
? throw new ArgumentNullException(nameof(source))
21
: (T)source.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.Invoke(source, null)!;
22
}
17
public T ActiveCopyOf() => source is null ? throw new ArgumentNullException(nameof(source)) : (T)source.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.Invoke(source, null)!;
23
18
24
19
/// <summary>
25
20
/// 进行静态拷贝
@@ -28,66 +23,34 @@ public static class ObjectExtension
28
23
public T? StaticCopyOf()
29
24
{
30
25
if (source is null)
31
{
32
return default;
33
}
26
return null;
34
27
var fields = typeof(T).GetFields();
35
28
var properties = typeof(T).GetProperties();
36
29
var newObject = Activator.CreateInstance<T>();
37
30
foreach (var property in properties)
38
{
39
31
property.SetValue(newObject, property.GetValue(source));
40
}
41
32
foreach (var field in fields)
42
{
43
33
field.SetValue(newObject, field.GetValue(source));
44
}
45
34
return newObject;
46
35
}
47
}
48
36
49
/// <summary>
50
/// 比较两个对象的属性是否完全相同而非对象本身相同
51
/// </summary>
52
/// <typeparam name="T"></typeparam>
53
/// <param name="obj1"></param>
54
/// <param name="obj2"></param>
55
/// <returns></returns>
56
public static bool AboutEqual<T>(this T obj1, T obj2)
57
{
58
if (obj1 is null && obj2 is null)
59
{
60
return true;
61
}
62
63
if (obj1 is null || obj2 is null)
64
{
65
return false;
66
}
67
68
Type type = typeof(T);
69
var properties = type.GetProperties();
70
var fields = type.GetFields();
71
foreach (var property in properties)
37
/// <summary>
38
/// 比较两个对象的属性是否完全相同而非对象本身相同
39
/// </summary>
40
/// <param name="obj2"></param>
41
/// <returns></returns>
42
public bool AboutEqual(T? obj2)
72
43
{
73
var value1 = property.GetValue(obj1);
74
var value2 = property.GetValue(obj2);
75
76
if (!Equals(value1, value2))
77
{
44
if (source is null && obj2 is null)
45
return true;
46
if (source is null || obj2 is null)
78
47
return false;
79
}
80
}
81
foreach (var field in fields)
82
{
83
var value1 = field.GetValue(obj1);
84
var value2 = field.GetValue(obj2);
85
86
if (!Equals(value1, value2))
87
{
48
Type type = typeof(T);
49
var properties = type.GetProperties();
50
var fields = type.GetFields();
51
if ((from property in properties let value1 = property.GetValue(source) let value2 = property.GetValue(obj2) where !Equals(value1, value2) select value1).Any())
88
52
return false;
89
}
53
return !(from field in fields let value1 = field.GetValue(source) let value2 = field.GetValue(obj2) where !Equals(value1, value2) select value1).Any();
90
54
}
91
return true;
92
55
}
93
56
}
@@ -122,6 +122,19 @@ public static class ReflectionExtension
122
122
var property = type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static);
123
123
property?.SetValue(null, value);
124
124
}
125
126
/// <summary>
127
/// 调用某个类中的某个私有静态方法
128
/// </summary>
129
/// <typeparam name="T"></typeparam>
130
/// <param name="methodName">方法名称</param>
131
/// <param name="parameters">传入参数</param>
132
/// <returns></returns>
133
public T? InvokePrivateStaticMethod<T>(string methodName, params object[] parameters)
134
{
135
var method = type.GetMethod(methodName);
136
return (T?)method?.Invoke(null, parameters);
137
}
125
138
}
126
139
127
140
/// <param name="obj"></param>
@@ -151,18 +164,4 @@ public static class ReflectionExtension
151
164
method?.Invoke(obj, parameters);
152
165
}
153
166
}
154
155
/// <summary>
156
/// 调用某个类中的某个私有静态方法
157
/// </summary>
158
/// <typeparam name="T"></typeparam>
159
/// <param name="type"></param>
160
/// <param name="methodName">方法名称</param>
161
/// <param name="parameters">传入参数</param>
162
/// <returns></returns>
163
public static T? InvokePrivateStaticMethod<T>(this Type type, string methodName, params object[] parameters)
164
{
165
var method = type.GetMethod(methodName);
166
return (T?)method?.Invoke(null, parameters);
167
}
168
167
}
@@ -76,6 +76,66 @@ public static partial class StringExtension
76
76
{
77
77
return IdCardRegex().IsMatch(telephoneNum);
78
78
}
79
80
/// <summary>
81
/// 判断字符串是否为邮箱地址
82
/// </summary>
83
/// <returns></returns>
84
public bool IsValidEmail()
85
{
86
if (string.IsNullOrWhiteSpace(telephoneNum))
87
return false;
88
89
try
90
{
91
telephoneNum = Regex.Replace(telephoneNum, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
92
var validDomain = new System.Net.Mail.MailAddress(telephoneNum).Host;
93
return Regex.IsMatch(telephoneNum, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)[0-9a-zA-Z]\@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,}))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
94
}
95
catch (FormatException)
96
{
97
return false;
98
}
99
}
100
101
/// <summary>
102
/// 验证是否是URL链接
103
/// </summary>
104
/// <returns></returns>
105
public bool IsURL()
106
{
107
string pattern = @"^(https?|ftp|file|ws)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$";
108
return IsMatch(pattern, telephoneNum);
109
}
110
111
/// <summary>
112
/// 字符串实际显示的长度
113
/// </summary>
114
/// <returns></returns>
115
public int DisplayLength()
116
{
117
int lengthCount = 0;
118
var splits = telephoneNum.ToCharArray();
119
for (int i = 0; i < splits.Length; i++)
120
{
121
if (splits[i] == '\t')
122
{
123
lengthCount += 8 - lengthCount % 8;
124
}
125
else
126
{
127
if (splits[i] > 255)
128
{
129
lengthCount += 2;
130
}
131
else
132
{
133
lengthCount += 1;
134
}
135
}
136
}
137
return lengthCount;
138
}
79
139
}
80
140
81
141
/// <param name="str"></param>
@@ -94,27 +154,6 @@ public static partial class StringExtension
94
154
public bool IsNullOrWhiteSpace() => string.IsNullOrWhiteSpace(str);
95
155
}
96
156
97
/// <summary>
98
/// 判断字符串是否为邮箱地址
99
/// </summary>
100
/// <param name="emailString"></param>
101
/// <returns></returns>
102
public static bool IsValidEmail(this string emailString)
103
{
104
if (string.IsNullOrWhiteSpace(emailString))
105
return false;
106
107
try
108
{
109
emailString = Regex.Replace(emailString, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
110
var validDomain = new System.Net.Mail.MailAddress(emailString).Host;
111
return Regex.IsMatch(emailString, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)[0-9a-zA-Z]\@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,}))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
112
}
113
catch (FormatException)
114
{
115
return false;
116
}
117
}
118
157
private static string DomainMapper(Match match)
119
158
{
120
159
var idn = new IdnMapping();
@@ -122,16 +161,7 @@ public static partial class StringExtension
122
161
domainName = idn.GetAscii(domainName);
123
162
return match.Groups[1].Value + domainName;
124
163
}
125
/// <summary>
126
/// 验证是否是URL链接
127
/// </summary>
128
/// <param name="str">指定字符串</param>
129
/// <returns></returns>
130
public static bool IsURL(this string str)
131
{
132
string pattern = @"^(https?|ftp|file|ws)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$";
133
return IsMatch(pattern, str);
134
}
164
135
165
/// <summary>
136
166
/// 判断一个字符串,是否匹配指定的表达式(区分大小写的情况下)
137
167
/// </summary>
@@ -147,7 +177,7 @@ public static partial class StringExtension
147
177
}
148
178
149
179
/// <param name="str"></param>
150
extension(string str)
180
extension(string? str)
151
181
{
152
182
/// <summary>
153
183
/// 提取字符串中的URL链接
@@ -309,35 +339,6 @@ public static partial class StringExtension
309
339
}
310
340
}
311
341
312
/// <summary>
313
/// 字符串实际显示的长度
314
/// </summary>
315
/// <param name="str"></param>
316
/// <returns></returns>
317
public static int DisplayLength(this string str)
318
{
319
int lengthCount = 0;
320
var splits = str.ToCharArray();
321
for (int i = 0; i < splits.Length; i++)
322
{
323
if (splits[i] == '\t')
324
{
325
lengthCount += 8 - lengthCount % 8;
326
}
327
else
328
{
329
if (splits[i] > 255)
330
{
331
lengthCount += 2;
332
}
333
else
334
{
335
lengthCount += 1;
336
}
337
}
338
}
339
return lengthCount;
340
}
341
342
/// <summary>
342
343
/// 随机生成指定长度的字符串
343
344
/// </summary>
@@ -58,7 +58,7 @@ public static class TaskExtension
58
58
/// <param name="autoOutPut">自动输出</param>
59
59
/// <param name="timerName">该次计时标识名</param>
60
60
/// <returns></returns>
61
public static TimeSpan CTime(this Action action, bool autoOutPut = true, string timerName = "无标识名计时器")
61
public static TimeSpan CTime(this Action? action, bool autoOutPut = true, string timerName = "无标识名计时器")
62
62
{
63
63
var timeCounter = new Stopwatch();
64
64
timeCounter.Start();
@@ -95,7 +95,7 @@ public abstract class XFECode
95
95
/// <param name="autoOutPut">自动输出</param>
96
96
/// <param name="timerName">该次计时标识名</param>
97
97
/// <returns></returns>
98
public static TimeSpan CTime(Action action, bool autoOutPut = true, string timerName = "无标识名计时器")
98
public static TimeSpan CTime(Action? action, bool autoOutPut = true, string timerName = "无标识名计时器")
99
99
{
100
100
var timeCounter = new Stopwatch();
101
101
timeCounter.Start();
@@ -125,7 +125,7 @@ public abstract class XFECode
125
125
/// <param name="autoOutPut">自动输出</param>
126
126
/// <param name="timerName">该次计时标识名</param>
127
127
/// <returns></returns>
128
public static async Task<TimeSpan> CTimeAsync(Func<Task> action, bool autoOutPut = true, string timerName = "无标识名计时器")
128
public static async Task<TimeSpan> CTimeAsync(Func<Task>? action, bool autoOutPut = true, string timerName = "无标识名计时器")
129
129
{
130
130
var timeCounter = new Stopwatch();
131
131
timeCounter.Start();