Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MemberInfo.GetCustomAttributes扩展重载_C# - Fatal编程技术网

C# MemberInfo.GetCustomAttributes扩展重载

C# MemberInfo.GetCustomAttributes扩展重载,c#,C#,我注意到包系统中有两个方法(一个类方法和一个扩展方法)具有相同的签名,但返回类型不同。类MemberInfo的反射: 类方法: public abstract object[] GetCustomAttributes(Type attributeType, bool inherit) 扩展方法(内部): 公共静态IEnumerable GetCustomAttributes(此MemberInfo元素,类型attributeType,bool inherit) 我知道用这些参数调用该方法将始

我注意到包系统中有两个方法(一个类方法和一个扩展方法)具有相同的签名,但返回类型不同。类MemberInfo的反射:

类方法:

public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)
扩展方法(内部):

公共静态IEnumerable GetCustomAttributes(此MemberInfo元素,类型attributeType,bool inherit)
我知道用这些参数调用该方法将始终调用类方法,所以我只是想知道:

如何调用扩展方法

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

您是对的,存在并且实际上具有相同的参数集

如果查看每种方法的引用源,可以看到扩展方法实际上委托回。该方法最终将返回到
MemberInfo.GetCustomAttributes


那么这两者之间有功能上的区别吗?不,不是真的。那么,这种扩展方法存在的原因是什么?不幸的是,我没有任何线索。
CustomAttributeExtensions
的主要好处是通用重载,它允许您返回类型化属性,因此我认为在通常情况下,您实际上不希望使用
GetCustomAttributes

在框架中进行这种复制并不完全是一种功能。但这是一个困难的地方,他们不得不在.NET4.5中添加扩展方法。最容易从版本信息块中的MSDN文章底部看到。扩展方法在UWP和电话项目中可用,而传统方法不可用

根本原因是CLR 4.5中内置的语言投影。这使得WinRT和CLR类型之间的巨大差异高度不可见。WinRT仍然会诞生,比它已经诞生的时间还要长,如果程序员们有任何迹象表明它实际上是为UWP提供动力的幕后COM:)隐藏得非常好,但是类型类与CLR的结合太紧密了,他们必须提供TypeInfo类作为替代。以及弥补api差距的扩展方法


如果您不以UWP为目标,那么扩展方法就没有多大用处,应该倾向于传统方法。扩展方法。

您可以像调用静态方法一样调用它<代码>CustomAttributeExtensions.GetCustomAttributes(元素、属性、继承)如果您能给我们提供更多的上下文,这会有所帮助-这
CustomAttributeExtensions
类在哪里?这是参考
public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)