简体   繁体   English

如何将 object 转换为 IAsyncEnumerable?

[英]How to cast object to IAsyncEnumerable?

I'm building a logging filter for my SignalR hub.我正在为我的 SignalR 集线器构建一个日志过滤器。 If the invocation is of type IAsyncEnumerable , I want to log every action that it yields.如果调用是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;
        }
    }
}

I want to cast object to IAsyncEnumerable , but since IAsyncEnumerable is generic, I'm not sure how to do this.我想将objectIAsyncEnumerable ,但由于IAsyncEnumerable是通用的,我不知道该怎么做。

Since the type parameter of IAsyncEnumerable<T> is covariant you can cast it to IAsyncEnumerable<object> in case the type of T is unknown.由于IAsyncEnumerable<T>的类型参数是协变的,因此您可以将其强制转换为IAsyncEnumerable<object>以防T的类型未知。

So the easiest way to do this would be using is :所以最简单的方法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>
            ...
        }
    }
}

Update更新

As @Dai pointed out, this approach is not working in case of IAsyncEnumerable<T> of value types.正如@Dai 指出的那样,这种方法在IAsyncEnumerable<T>值类型的情况下不起作用。 It should work fine if you are sure that you are only dealing with reference types.如果您确定您只处理引用类型,它应该可以正常工作。

The reason is explained here .原因在这里解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM