简体   繁体   English

如何使用Reflection调用类型为“private async Task”的方法

[英]How to use Reflection to call a method of type “private async Task”

I have a class called PageProcessor with a method 我有一个名为PageProcessor的类,带有一个方法

private static async Task InsertPosts(IEnumerable<LrcPost> posts)
{
   // ...
}

and I'm trying to call it in one of my unit tests like 而我正试图在我的单元测试之一中调用它

PageProcessor processor = new PageProcessor();
MethodInfo dynMethod = processor.GetType()
    .GetMethod
    (
        "InsertPosts",
        BindingFlags.NonPublic | BindingFlags.Instance
    );

dynMethod.Invoke(processor, new object[] { posts }); dynMethod.Invoke(processor,new object [] {posts});

but am getting an NRE. 但我得到一个NRE。 Any idea why? 知道为什么吗?

The method info is null when you try to access it because it is a static member and not an instance member. 当您尝试访问它时,方法info为null,因为它是静态成员而不是实例成员。

Access the method as static member and not an instance member. 以静态成员而非实例成员的身份访问该方法。 Also because it is static an instance is not needed to invoke method. 另外,因为它是静态的,所以不需要实例来调用方法。

var type = typeof(PageProcessor);
var method = type.GetMethod("InsertPosts", BindingFlags.NonPublic | BindingFlags.Static);
var task = method.Invoke(null, new object[] { posts }) as Task;

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

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