在.NET 2.0 C#扩展方法 [英] C# Extension methods in .NET 2.0

查看:117
本文介绍了在.NET 2.0 C#扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发现了几个链接,这使得扩展方式方法的工作.NET2.0(的飞蛾,的不和谐和放大器;韵堆栈溢出)。我也听到隐约从一个同事,这会导致一些问题库什么的?这样的话?此外,各3使用不同的方法:

I have found several links to methods of making extension methods work in .NET2.0 (The moth, Discord & Rhyme, Stack Overflow). I have also heard vaguely from a colleague that this causes some problems with libraries or something? Is this the case? Also all 3 use different methods:

飞蛾

namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute : Attribute { }
}

龃龉和韵

namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
  public class ExtensionAttribute : Attribute {}
}

堆栈溢出

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}

请告诉我这些方法之间的区别,以及哪一个,你会推荐?

Whats the difference between these methods, and which one would you recommend?

推荐答案

归根结底,是不会太大的差别;你可能会说,一个运行期匹配是preferred,但是的理想的答案是,在以后的日子就可以使用不同版本的同一个容易混淆,否则切换到.NET 3.5(属性范围等)。

Ultimately it isn't going to make much difference; you could argue that the one that matches the runtime is preferred, but the ideal answer is to switch to .NET 3.5 (otherwise at a later date it can get confusing with different versions of the same attribute in scope etc).

[AttributeUsage] 将prevent它被连接到的东西,它不会做任何事情 - 但它不会做aything的本身的反正...

The [AttributeUsage] will prevent it being attached to things where it won't do anything - but it won't do aything by itself anyway...

看着对元数据类型,确切属性的使用似乎是最喜欢的计算器变种 - 但最终,这不是非常重要的 - 在名称命名空间的是所有该事项(并且是由属性继承)。

Looking at metadata against the type, the exact attribute usage seems most like the stackoverflow variant - but ultimately this isn't hugely important - the name and namespace is all that matters (and that it inherits from Attribute).

这篇关于在.NET 2.0 C#扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆