【问题标题】:MemberInfo.GetCustomAttributes extensions overloadMemberInfo.GetCustomAttributes 扩展重载
【发布时间】:2017-07-07 07:45:05
【问题描述】:

我注意到类 MemberInfo 的 System.Reflection 包中有两个方法(一个类方法和一个扩展方法)具有相同的签名但返回类型不同:

类方法:

public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)

扩展方法(在CustomAttributeExtensions内):

public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)

我知道用这样的参数调用那个方法总是会调用类方法,所以我只是想知道:

如何调用扩展方法?

最重要的是,定义与类方法具有相同签名的扩展的目的是什么?

【问题讨论】:

  • 您可以将其称为静态方法。 CustomAttributeExtensions.GetCustomAttributes(element, attribute, inherit);
  • 如果你能给我们更多的背景信息会有所帮助 - 这个 CustomAttributeExtensions 类在哪里?

标签: c#


【解决方案1】:

在框架中存在这种重复并不完全是一个特性。但这是一个困难重重的地方,他们不得不在 .NET 4.5 中添加扩展方法。从版本信息块中的 MSDN 文章底部最容易看到。扩展方法可用于 UWP 和 Phone 项目,旧方法不可用。

根本原因是在 4.5 中内置于 CLR 中的语言投影。它使 WinRT 和 CLR 类型之间相当大的差异变得非常不可见。如果程序员有任何暗示,它实际上是为 UWP 提供动力的引擎盖下的 COM 的话,WinRT 将是死胎 :) 隐藏得很好,但是 Type 类与 CLR 的结合过于紧密,他们不得不提供 TypeInfo 类作为替代。以及弥合 api 差距的扩展方法。

如果您不以 UWP 为目标,那么您对扩展方法没有太多用处,应该支持旧方法。扩展方法is about 30% slower

【讨论】:

    【解决方案2】:

    你是对的,MemberInfo.GetCustomAttributesCustomAttributeExtensions.GetCustomAttributes 的参数集实际上是相同的。

    如果您查看每个的参考源,您会发现扩展方法实际上委托回Attribute.GetCustomAttribute。而那个方法最终会回到MemberInfo.GetCustomAttributes

    那么这两者在功能上有区别吗?不,不是。那么这种扩展方式存在的原因是什么呢?不幸的是,我不知道。 CustomAttributeExtensions 的主要好处是泛型重载,它允许您返回类型化的属性,所以我认为您实际上并不想在通常情况下使用 GetCustomAttributes

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2013-01-20
      相关资源
      最近更新 更多