Skip to content

Commit ac112e0

Browse files
committed
IsBuffered()的UnsafeAccessor适配
1 parent 9742205 commit ac112e0

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

WebApiClientCore/ApiResponseContextExtensions.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,7 @@ public static class ApiResponseContextExtensions
5454
else
5555
{
5656
var utf8Json = await content.ReadAsByteArrayAsync().ConfigureAwait(false);
57-
return utf8Json.Length == 0
58-
? objType.DefaultValue()
59-
: JsonSerializer.Deserialize(utf8Json, objType, options);
57+
return utf8Json.Length == 0 ? objType.DefaultValue() : JsonSerializer.Deserialize(utf8Json, objType, options);
6058
}
6159
}
6260

WebApiClientCore/System.Net.Http/HttpContentExtensions.cs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Reflection;
2+
using System.Runtime.CompilerServices;
23
using System.Text;
34
using System.Threading.Tasks;
45
using WebApiClientCore.Exceptions;
@@ -11,31 +12,48 @@ namespace System.Net.Http
1112
/// </summary>
1213
public static class HttpContentExtensions
1314
{
15+
private const string IsBufferedPropertyName = "IsBuffered";
16+
private const string IsBufferedGetMethodName = "get_IsBuffered";
17+
1418
/// <summary>
1519
/// IsBuffered字段
1620
/// </summary>
17-
private static readonly Func<HttpContent, bool>? isBuffered;
21+
private static readonly Func<HttpContent, bool>? isBufferedFunc;
1822

1923
/// <summary>
2024
/// 静态构造器
2125
/// </summary>
2226
static HttpContentExtensions()
2327
{
24-
var property = typeof(HttpContent).GetProperty("IsBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
28+
var property = typeof(HttpContent).GetProperty(IsBufferedPropertyName, BindingFlags.Instance | BindingFlags.NonPublic);
2529
if (property != null)
2630
{
27-
isBuffered = LambdaUtil.CreateGetFunc<HttpContent, bool>(property);
31+
#if NET8_0_OR_GREATER
32+
if (property.GetGetMethod(nonPublic: true)?.Name == IsBufferedGetMethodName)
33+
{
34+
isBufferedFunc = GetIsBuffered;
35+
}
36+
#endif
37+
if (isBufferedFunc == null)
38+
{
39+
isBufferedFunc = LambdaUtil.CreateGetFunc<HttpContent, bool>(property);
40+
}
2841
}
2942
}
3043

44+
#if NET8_0_OR_GREATER
45+
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = IsBufferedGetMethodName)]
46+
private static extern bool GetIsBuffered(HttpContent httpContent);
47+
#endif
48+
3149
/// <summary>
3250
/// 获取是否已缓存数据
3351
/// </summary>
3452
/// <param name="httpContent"></param>
3553
/// <returns></returns>
3654
public static bool? IsBuffered(this HttpContent httpContent)
3755
{
38-
return isBuffered?.Invoke(httpContent);
56+
return isBufferedFunc == null ? null : isBufferedFunc(httpContent);
3957
}
4058

4159
/// <summary>

0 commit comments

Comments
 (0)