C#2.0中的扩展方法

我需要什么命名空间才能使我的扩展工作

这是我的扩展方法


使用系统;
使用System.Collections.Generic;
使用System.Web;
使用System.Data;

命名空间MyUtilities
 {
     public static class DataReaderExtensions
     {
         public static DataTable ToDataTable(IDataReader reader)
         {
             DataTable table = new DataTable();
             table.Load(读取器);
            返回表;
         }
     }
 }

当我尝试像这样使用它

 Session [“Master”] = cust.GetCustomerOrderSummary((string)Session [“CustomerNumber”])。ToDataTable();

它不起作用。 这是.net 2.0

你不能。 C#2.0根本没有扩展方法。 您可以使用Visual Studio 2008中针对 .NET 2.0的C#3.0中的扩展方法,如我的“C#/ .NET版本”文章中所述,但您无法说服C#2.0编译器表现得好像它了解哪些扩展方法。

标签说.NET 2.0; 如果您使用的是C#3.0(即VS 2008)并且目标是.NET 2.0,则可以通过声明ExtensionAttribute – 或(更简单)引用LINQBridge来实现 。

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

有了这个,扩展方法将适用于带有C#3.0的.NET 2.0。

扩展方法在C#2中不起作用,因为它们依赖于C#3编译器。 C#3编译器知道如何从这里进行转换:

 foo.Bar() 

对此:

 ExtensionClass.Bar(foo) 

正如JS所说,C#2.0没有扩展方法。

此扩展方法也将定义为:

 public static DataTable ToDataTable(this IDataReader reader) 

尝试调用它:

 DataReaderExtensions.ToDataTable( cust.GetCustomerOrderSummary((string)Session["CustomerNumber"]) )