检查返回类型是否为 IEnumerable

发布于 2024-09-28 19:37:01 字数 149 浏览 0 评论 0原文

如何检查函数的返回类型是否为 IEnumerable?换句话说,我不想匹配 List,即使它实现了 IEnumerable。或者换句话说,如何检测函数是否延迟执行?

How can I check if the return type of a function is IEnumerable<T>? In other words, I don't want to match List<T>, even though it implements IEnumerable<T>. Or put even another way, how can I detect if a function has deferred execution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风蛊 2024-10-05 19:37:01

我假设您正在与 MethodInfo 进行交互?

Type returnType = methodInfo.ReturnType;
bool isEnumerable = returnType.IsGenericType && 
                    returnType.GetGenericTypeDefinition() == typeof(IEnumerable<>);

当然,仅仅因为它返回 IEnumerable 并不意味着它使用延迟执行(即 yield return),并且没有真正的方法可以在不反编译代码的情况下检查这一点。

I assume you are interacting with a MethodInfo?

Type returnType = methodInfo.ReturnType;
bool isEnumerable = returnType.IsGenericType && 
                    returnType.GetGenericTypeDefinition() == typeof(IEnumerable<>);

Of course, just because it returns IEnumerable doesn't mean it uses deferred execution (i.e. yield return) and there's no real way to check for that without decompiling the code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文