且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待在 WinRT 中使用反射调用的异步私有方法?

更新时间:2023-01-18 14:17:10

嗯,你需要使用方法返回的值.你知道类型吗?例如,如果它总是一个 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.