在.NET Framework 2.0中使用扩展方法

Amr*_*Amr 6 c# extension-methods visual-studio-2008 .net-2.0

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

Tom*_*ter 10

有一个丑陋的黑客让扩展方法在.Net 2.0中工作; 但最好将框架升级到3.5.

替代能源:1,2.

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

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