【问题标题】:Unable to get the "Add" method of a ColumnDefinitionCollection in UWP无法在 UWP 中获取 ColumnDefinitionCollection 的“添加”方法
【发布时间】:2017-02-20 13:33:33
【问题描述】:

在 Windows 通用应用程序的上下文中,并使用反射,我试图从 ColumnDefinitionCollection(内置类型)获取 Add 方法

所以我用这个:

type.GetRuntimeMethods().First(info => info.Name == "Add");

但它返回 null!

Contains 方法也会发生这种情况。它们都在ICollection<T> 中定义(IList<T> 派生自它)。

但是,如果我定义自己的派生自 IList<T> 的类,它会完美运行。

那么,如何获取 Add 方法的 MethodInfo 呢? ColumnDefinitionCollection 是否使用了一些技巧?也许与 COM 相关?

【问题讨论】:

  • 试试typeof(ColumnDefinitionCollection).GetMethod(nameof(IList.Add), BindingFlags.Instance | BindingFlags.Public);。这应该有效。您可能找不到该方法,因为它是由IList 实现的。反射通常会使搜索变平,因此将其限制为由类 ColumnDefinitionCollection 实现的方法。
  • @SharpShade 不幸的是,我的代码在没有你提到的方法的可移植类库上运行:(
  • 好吧,好吧。我还没有使用 PCL,但我认为我所说的仍然适用。 UWP 中的反射比普通的 .Net 应用程序更受限制,这就是您找不到我提到的方法的原因。尽管如此,我猜内部系统会使搜索变平,这就是为什么您看不到 Add 方法的原因。 编辑:好的,我错了。 GetRuntimeMethods 也应该显示继承的方法。
  • 试试typeof (ICollection<ColumnDefinition>).GetRuntimeMethods()
  • 你可以得到实现的接口并在那里搜索方法。像这样:type.GetTypeInfo().ImplementedInterfaces.SelectMany(x => x.GetRuntimeMethods())

标签: c# .net reflection com uwp


【解决方案1】:

我真的不知道为什么GetRuntimeMethods 没有返回所有方法。这是预期的行为吗?还是bug?

无论如何,一种解决方案(或者可能是一种变通方法)是获取该类型实现的接口,然后获取这些接口的方法,如下所示:

var methodsOfImplementedInterfaces = 
    type
        .GetTypeInfo()
        .ImplementedInterfaces
        .SelectMany(x => x.GetRuntimeMethods())
        .ToList();

在您的特定情况下,这将起作用,因为 Add 实际上是在 ICollection<T> 上定义的,它由 ColumnDefinitionCollection 实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2016-10-21
    • 2015-01-16
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多