Code Review 2

This commit is contained in:
龙腾猫跃 committed 2026-05-07 09:20:23 +08:00
1 parent 9158a69b62
commit 368280fcb5
8 files changed
+54 -45

No files matched your search

+29 -25
View File
@@ -11,14 +11,18 @@ public static class EnumerableExtensions {
/// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。 /// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
/// </summary> /// </summary>
public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) { public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
for (int i = list.Count - 1; i >= 0; i--) { // 反向遍历以保留最早出现的重复项 var seen = new List<T>();
if (!list.Skip(i + 1).Any(item => comparer(list[i], item))) yield return list[i]; foreach (var item in list) {
if (!seen.Any(s => comparer(s, item))) {
seen.Add(item);
yield return item;
}
} }
} }
/// <summary> /// <summary>
/// 按对象的指定值去重。 /// 按对象的指定值去重。
/// </summary> /// </summary>
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) { public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) {
var seen = new HashSet<TKey>(); var seen = new HashSet<TKey>();
foreach (var element in source) { foreach (var element in source) {
if (seen.Add(selector(element))) yield return element; if (seen.Add(selector(element))) yield return element;
@@ -27,7 +31,7 @@ public static class EnumerableExtensions {
/// <summary> /// <summary>
/// 按对象的指定值去重。 /// 按对象的指定值去重。
/// </summary> /// </summary>
public static ParallelQuery<T> DistinctBy<T, TKey>(this ParallelQuery<T> source, Func<T, TKey> selector) { public static ParallelQuery<TSource> DistinctBy<TSource, TKey>(this ParallelQuery<TSource> source, Func<TSource, TKey> selector) {
var seen = new ConcurrentDictionary<TKey, bool>(); var seen = new ConcurrentDictionary<TKey, bool>();
return source.Where(element => seen.TryAdd(selector(element), true)); return source.Where(element => seen.TryAdd(selector(element), true));
} }
@@ -40,16 +44,16 @@ public static class EnumerableExtensions {
/// 选择所有最大值对应的对象。 /// 选择所有最大值对应的对象。
/// 若没有元素则返回空列表。 /// 若没有元素则返回空列表。
/// </summary> /// </summary>
public static List<TKey> MaxByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
var results = new List<TKey>(); var results = new List<TSource>();
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results; if (!enumerator.MoveNext()) return results;
TKey maxItem = enumerator.Current; TSource maxItem = enumerator.Current;
TValue maxValue = selector(maxItem); TKey maxValue = selector(maxItem);
results.Add(maxItem); results.Add(maxItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current; TSource currentItem = enumerator.Current;
TValue currentValue = selector(currentItem); TKey currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(maxValue); int comparisonResult = currentValue.CompareTo(maxValue);
if (comparisonResult > 0) { if (comparisonResult > 0) {
maxValue = currentValue; maxValue = currentValue;
@@ -65,16 +69,16 @@ public static class EnumerableExtensions {
/// 选择所有最小值对应的对象。 /// 选择所有最小值对应的对象。
/// 若没有元素则返回空列表。 /// 若没有元素则返回空列表。
/// </summary> /// </summary>
public static List<TKey> MinByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
var results = new List<TKey>(); var results = new List<TSource>();
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results; if (!enumerator.MoveNext()) return results;
TKey minItem = enumerator.Current; TSource minItem = enumerator.Current;
TValue minValue = selector(minItem); TKey minValue = selector(minItem);
results.Add(minItem); results.Add(minItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current; TSource currentItem = enumerator.Current;
TValue currentValue = selector(currentItem); TKey currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(minValue); int comparisonResult = currentValue.CompareTo(minValue);
if (comparisonResult < 0) { if (comparisonResult < 0) {
minValue = currentValue; minValue = currentValue;
@@ -91,13 +95,13 @@ public static class EnumerableExtensions {
/// 选择最大值对应的对象。 /// 选择最大值对应的对象。
/// 若没有元素则返回 null。 /// 若没有元素则返回 null。
/// </summary> /// </summary>
public static TKey? MaxBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return default; if (!enumerator.MoveNext()) return default;
TKey maxItem = enumerator.Current; TSource maxItem = enumerator.Current;
TValue maxValue = selector(maxItem); TKey maxValue = selector(maxItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TValue value = selector(enumerator.Current); TKey value = selector(enumerator.Current);
if (value.CompareTo(maxValue) <= 0) continue; if (value.CompareTo(maxValue) <= 0) continue;
maxItem = enumerator.Current; maxItem = enumerator.Current;
maxValue = value; maxValue = value;
@@ -108,13 +112,13 @@ public static class EnumerableExtensions {
/// 选择最小值对应的对象。 /// 选择最小值对应的对象。
/// 若没有元素则返回 null。 /// 若没有元素则返回 null。
/// </summary> /// </summary>
public static TKey? MinBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) { return default; } if (!enumerator.MoveNext()) { return default; }
TKey minItem = enumerator.Current; TSource minItem = enumerator.Current;
TValue minValue = selector(minItem); TKey minValue = selector(minItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TValue value = selector(enumerator.Current); TKey value = selector(enumerator.Current);
if (value.CompareTo(minValue) >= 0) { continue; } if (value.CompareTo(minValue) >= 0) { continue; }
minItem = enumerator.Current; minItem = enumerator.Current;
minValue = value; minValue = value;
@@ -183,7 +187,7 @@ public static class EnumerableExtensions {
/// <summary> /// <summary>
/// 尝试从字典中获取某项,如果该项不存在,则返回默认值。 /// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
/// </summary> /// </summary>
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default!) public static TValue? GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default)
=> dict.TryGetValue(key, out var result) ? result : defaultValue; => dict.TryGetValue(key, out var result) ? result : defaultValue;
/// <summary> /// <summary>
+1 -1
View File
@@ -44,7 +44,7 @@ public static class ExceptionExtensions {
lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true)); lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true));
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName); if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
var stackLines = (currentEx.StackTrace?.ReplaceLineEndings("\r", true).Split('\r') ?? []) var stackLines = (currentEx.StackTrace?.ReplaceLineEndings("\r", true).Split('\r') ?? [])
.Select(l => l.BeforeFirst("(") + l.AfterFirst(")")) .Select(l => l.BeforeLast("(") + l.AfterLast(")"))
.Distinct(); .Distinct();
lines.AddRange(stackLines); lines.AddRange(stackLines);
} else { } else {
+1 -1
View File
@@ -189,7 +189,7 @@ public static class StringExtensions {
/// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。 /// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
/// </summary> /// </summary>
public static string EnsureLength(this string? str, char code, int length) { public static string EnsureLength(this string? str, char code, int length) {
if (str == null) str = ""; str ??= "";
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code); return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
} }
+6 -2
View File
@@ -131,7 +131,10 @@ public class BaseLogger {
} }
public virtual void Log(Exception ex, string? message, LogLevel level, LogBehavior behavior, string filePath) { public virtual void Log(Exception ex, string? message, LogLevel level, LogBehavior behavior, string filePath) {
if (MinLevel > level) return; if (MinLevel > level) return;
if (ex is ThreadInterruptedException) return; if (ex is ThreadInterruptedException) {
Thread.CurrentThread.Interrupt();
return;
}
try { try {
var formattedMessage = (message is null ? "" : $"{message}:") + ex.GetDisplay(true); var formattedMessage = (message is null ? "" : $"{message}:") + ex.GetDisplay(true);
formattedMessage = Format(formattedMessage, level, filePath, ex); formattedMessage = Format(formattedMessage, level, filePath, ex);
@@ -230,7 +233,7 @@ public class FileLogger : BaseLogger, IDisposable {
writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true }; writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
writerAvailable = true; writerAvailable = true;
Logger.Info("日志初始化成功"); Logger.Info("日志初始化成功");
while (true) { while (writerAvailable) {
queuedEvent.WaitOne(); queuedEvent.WaitOne();
Flush(); Flush();
} }
@@ -246,5 +249,6 @@ public class FileLogger : BaseLogger, IDisposable {
writerAvailable = false; writerAvailable = false;
if (writer is not null) ((IDisposable) writer).Dispose(); if (writer is not null) ((IDisposable) writer).Dispose();
queuedEvent.Dispose(); queuedEvent.Dispose();
GC.SuppressFinalize(this);
} }
} }
+9 -10
View File
@@ -6,8 +6,7 @@ public static class EscapeUtils {
/// <summary> /// <summary>
/// WPF XML 转义。 /// WPF XML 转义。
/// </summary> /// </summary>
public static string? XmlEscape(string? str) { public static string XmlEscape(string str) {
if (str is null) return null;
if (str.StartsWithF("{")) str = "{}" + str; // #4187 if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;") .Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
@@ -34,7 +33,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="Regex.Escape"/>。 /// 等同于 <see cref="Regex.Escape"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexEscape(string value) public static string RegexEscape(string value)
=> Regex.Escape(value); => Regex.Escape(value);
/// <summary> /// <summary>
@@ -42,7 +41,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="Regex.Unescape"/>。 /// 等同于 <see cref="Regex.Unescape"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexUnescape(string value) public static string RegexUnescape(string value)
=> Regex.Unescape(value); => Regex.Unescape(value);
/// <summary> /// <summary>
@@ -50,7 +49,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="Uri.EscapeDataString"/>。 /// 等同于 <see cref="Uri.EscapeDataString"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlEscape(string value) public static string UrlEscape(string value)
=> Uri.EscapeDataString(value); => Uri.EscapeDataString(value);
/// <summary> /// <summary>
@@ -58,7 +57,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="Uri.UnescapeDataString"/>。 /// 等同于 <see cref="Uri.UnescapeDataString"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlUnescape(string value) public static string UrlUnescape(string value)
=> Uri.UnescapeDataString(value); => Uri.UnescapeDataString(value);
/// <summary> /// <summary>
@@ -66,7 +65,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="WebUtility.UrlEncode"/>。 /// 等同于 <see cref="WebUtility.UrlEncode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlEscape(string value) public static string FormUrlEscape(string value)
=> WebUtility.UrlEncode(value); => WebUtility.UrlEncode(value);
/// <summary> /// <summary>
@@ -74,7 +73,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="WebUtility.UrlDecode"/>。 /// 等同于 <see cref="WebUtility.UrlDecode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlUnescape(string value) public static string FormUrlUnescape(string value)
=> WebUtility.UrlDecode(value); => WebUtility.UrlDecode(value);
/// <summary> /// <summary>
@@ -82,7 +81,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="WebUtility.HtmlEncode"/>。 /// 等同于 <see cref="WebUtility.HtmlEncode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlEscape(string value) public static string HtmlEscape(string value)
=> WebUtility.HtmlEncode(value); => WebUtility.HtmlEncode(value);
/// <summary> /// <summary>
@@ -90,7 +89,7 @@ public static class EscapeUtils {
/// 等同于 <see cref="WebUtility.HtmlDecode"/>。 /// 等同于 <see cref="WebUtility.HtmlDecode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlUnescape(string value) public static string HtmlUnescape(string value)
=> WebUtility.HtmlDecode(value); => WebUtility.HtmlDecode(value);
} }
+4 -2
View File
@@ -35,7 +35,7 @@ public static class FileUtils {
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。 /// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, Stream stream) { public static void Write(string filePath, Stream stream) {
using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath)); using FileStream fileStream = FileUtils.CreateAsStream(filePath);
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin); if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})"); Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})");
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
@@ -85,7 +85,9 @@ public static class FileUtils {
Run(target); Run(target);
} else { } else {
System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常 System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); } }); var thread = new Thread(
() => { try { Run(target); } catch (Exception ex) { internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); } })
{ IsBackground = true, Name = nameof(DeleteToRecycleBin) };
thread.SetApartmentState(ApartmentState.STA); thread.SetApartmentState(ApartmentState.STA);
thread.Start(); thread.Start();
thread.Join(); thread.Join();
+2 -2
View File
@@ -7,9 +7,9 @@ public class HttpRequestCodeException(string message, HttpStatusCode statusCode,
/// <summary> /// <summary>
/// HTTP 请求的状态码。 /// HTTP 请求的状态码。
/// </summary> /// </summary>
public HttpStatusCode StatusCode { get; set; } = statusCode; public HttpStatusCode StatusCode { get; } = statusCode;
/// <summary> /// <summary>
/// 远程服务器给予的回复。 /// 远程服务器给予的回复。
/// </summary> /// </summary>
public string? Response { get; set; } = response; public string? Response { get; } = response;
} }
+2 -2
View File
@@ -17,7 +17,7 @@ public abstract class TestWithFolder {
$"{GetType().Name}-{Guid.NewGuid()}", $"{GetType().Name}-{Guid.NewGuid()}",
"文件夹 Dir_!@#$%^&()_+={}[];',_", "文件夹 Dir_!@#$%^&()_+={}[];',_",
new string('X', 200), new string('X', 200)) + @"\"; new string('X', 200), new string('X', 200)) + @"\";
Directory.CreateDirectory(@"\\?\" + tempFolder); DirectoryUtils.Create(tempFolder);
} }
/// <summary> /// <summary>
@@ -26,7 +26,7 @@ public abstract class TestWithFolder {
public string GetTestFile(string fileName) { public string GetTestFile(string fileName) {
var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName); var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
var distPath = Path.Combine(tempFolder, Path.GetFileName(sourceFilePath)); var distPath = Path.Combine(tempFolder, Path.GetFileName(sourceFilePath));
File.Copy(sourceFilePath, @"\\?\" + distPath); FileUtils.Copy(sourceFilePath, distPath);
return distPath; return distPath;
} }