在 .NET Framework 2.0 中使用扩展方法 [英] Using Extension Methods with .NET Framework 2.0

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

问题描述

在 Visual Studio 2008 下
我可以创建一个扩展方法来在 .NET Framework 2.0 项目下工作吗?

Under Visual Studio 2008
Can I create an Extension Method to work under a .NET Framework 2.0 project?

推荐答案

有一个 丑陋的 hack 使扩展方法在 .Net 2.0 中工作;但最好只是将您的框架升级到 3.5.

There is an ugly hack that gets Extension methods working in .Net 2.0; but it would better just to upgrade your framework to 3.5.

替代来源:12.

简而言之(来自链接#2):扩展方法只是标有 [Extension] 属性的普通静态方法.这个属性实际上只是编译器在幕后添加的.在 .NET 3.5 中,它存在于 System.Core 中,因此只需像这样定义自己的属性:

In short (from link #2): Extension methods are just normal static methods tagged with the [Extension] attribute. This attribute is actually just added by the compiler behind the scenes. In .NET 3.5, it lives in System.Core, so just define your own attribute like this:

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

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

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