![](/img/trans.png)
[英]How to cast object of type 'X.PagedList.StaticPagedList` to type 'System.Collections.Generic.IAsyncEnumerable`
[英]How to cast object to IAsyncEnumerable?
我正在為我的 SignalR 集線器構建一個日志過濾器。 如果調用是IAsyncEnumerable
類型,我想記錄它產生的每個操作。
public class LogFilter : IHubFilter
{
private static readonly ILogger _log = Log.ForContext<LogFilter>();
public async ValueTask<object> InvokeMethodAsync(
HubInvocationContext invocationContext,
Func<HubInvocationContext, ValueTask<object>> next)
{
if (invocationContext.HubMethod.ReturnType.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>))
{
var ret = await next(invocationContext);
// Cast ret to IAsyncEnumerable.
// Iterate over items, yield each item and log something.
return ret;
}
}
}
我想將object
為IAsyncEnumerable
,但由於IAsyncEnumerable
是通用的,我不知道該怎么做。
由於IAsyncEnumerable<T>
的類型參數是協變的,因此您可以將其強制轉換為IAsyncEnumerable<object>
以防T
的類型未知。
所以最簡單的方法is
使用:
public class LogFilter : IHubFilter
{
private static readonly ILogger _log = Log.ForContext<LogFilter>();
public async ValueTask<object> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object>> next)
{
if (invocationContext.HubMethod.ReturnType is IAsyncEnumerable<object> enumerable)
{
// simply use the enumerable variable, it is already cast to IAsyncEnumerable<object>
...
}
}
}
正如@Dai 指出的那樣,這種方法在IAsyncEnumerable<T>
值類型的情況下不起作用。 如果您確定您只處理引用類型,它應該可以正常工作。
原因在這里解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.