【问题标题】:Unable to find private void generic function with GetMethod无法使用 GetMethod 找到私有 void 泛型函数
【发布时间】:2016-07-28 20:38:52
【问题描述】:

我有一个具有以下签名的函数:

private void Foo<TPoco>(IContext context, List<TPoco> pocos, DateTime modifiedDateTime)
    where TPoco : MyAbstractClass

我在 GetMethods() 中找不到这个函数。

基于此 SO 帖子 (GetMethod for generic method),我尝试了这些绑定标志:

GetType().GetMethods(BindingFlags.Public 
    | BindingFlags.NonPublic 
    | BindingFlags.Instance 
    | BindingFlags.Static 
    | BindingFlags.FlattenHierarchy
)

这会在类中找到 14 个其他方法,但不是这个。它确实找到了这个方法:

protected void Bar<TContext, TPoco>(List<TPoco> pocosToPersist, TContext context)
    where TContext : IContext, new()
    where TPoco : MyAbstractClass

所以唯一的区别是访问级别 - 但是我可以看到其他私有功能。

即使我将绑定标志更改为更简单的东西(据我了解,这不应该使 new 项目可见):

GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance )

我还是没有看到这个功能。

【问题讨论】:

  • 您的最后一次尝试应该可以完美运行。你在什么对象上调用GetType
  • 问题一定出在其他地方。将函数和反射调用复制到新项目或 .Net Fiddle 之类的东西中,您将看到您在此处发布的代码完美无缺。
  • 是的,你们都说得对——私有函数在一个抽象类中,所以 GetType() 得到的类型与我预期的不同。

标签: c# reflection


【解决方案1】:

正如帖子中的 cmets 所指出的那样,代码应该有效。问题是我定义函数的类是抽象的,所以我找不到私有函数。

如果我执行this.GetType().BaseType.GetMethods( BindingFlags.NonPublic | BindingFlags.Instance),则函数会按预期显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多