如何等待在 WinRT 中使用反射调用的异步私有方法? [英] How to await an async private method invoked using reflection in WinRT?

查看:30
本文介绍了如何等待在 WinRT 中使用反射调用的异步私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 WinRT 应用编写单元测试,我能够使用它调用非异步私有方法:

I'm writing unit tests for a WinRT app, and I am able to invoke non-async private methods using this:

TheObjectClass theObject = new TheObjectClass();
Type objType = typeof(TheObjectClass);
objType.GetTypeInfo()
       .GetDeclaredMethod("ThePrivateMethod")
       .Invoke(theObject, null);

然而,如果有问题的私有方法是 async,代码将继续执行而不等待它完成.

However, if the private method in question is async, the code will continue execution without waiting for it to finish.

我如何为此添加await 功能?

How do I add await functionality to this?

推荐答案

嗯,你需要使用方法返回的值.你知道类型吗?例如,如果它总是一个 Task,你可以使用:

Well you need to use the value returned by the method. Do you know the type? For example, if it's always a Task, you could use:

await (Task) objType.GetTypeInfo()
                    .GetDeclaredMethod("ThePrivateMethod")
                    .Invoke(theObject, null);

如果您不知道返回类型但知道它是可等待的,您可以使用动态类型:

If you don't know the return type but know it will be awaitable, you could use dynamic typing:

await (dynamic) objType.GetTypeInfo()
                       .GetDeclaredMethod("ThePrivateMethod")
                       .Invoke(theObject, null);

我会尝试首先避免在单元测试中通过反射来调用私有方法.您可以通过公共(或内部)API 间接测试它吗?这通常更可取.

I would try to avoid having to call a private method by reflection in your unit tests in the first place though. Can you test it indirectly via the public (or internal) API? That's generally preferable.

这篇关于如何等待在 WinRT 中使用反射调用的异步私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆