如何在等待WinRT的使用反射调用的异步私有方法? [英] How to await an async private method invoked using reflection in 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);
不过,如果有问题的私有方法异步
中,code将继续执行,而不必等待它完成。
However, if the private method in question is async
, the code will continue execution without waiting for it to finish.
我如何添加的await
功能呢?
推荐答案
那么你需要使用该方法返回的值。你知道是什么类型?例如,如果它总是一个工作
,你可以使用:
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);
如果您不知道返回类型,但知道这将是awaitable,您可以使用动态类型:
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间接地测试它?这是一般preferable。
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屋!