2009-04-01 19 views
11

Co nazw muszę dostać moje rozszerzenie do pracymetodę rozszerzenia w C# 2.0

Tu jest moja metoda Extension

 

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Data; 

namespace MyUtilities 
{ 
    public static class DataReaderExtensions 
    { 
     public static DataTable ToDataTable(IDataReader reader) 
     { 
      DataTable table = new DataTable(); 
      table.Load(reader); 
      return table; 
     } 
    } 
} 

Kiedy próbuję użyć go w tak

 
Session["Master"] = cust.GetCustomerOrderSummary((string)Session["CustomerNumber"]).ToDataTable(); 

to nie działa. To jest .net 2.0

Odpowiedz

31

Nie możesz. C# 2.0 w ogóle nie ma żadnych metod rozszerzania. Możesz użyć metod rozszerzeń z C# 3.0 w Visual Studio 2008 targetowania .NET 2.0, jak opisano w moim "C#/.NET versions" article, ale nie możesz przekonać kompilatora C# 2.0, aby działał tak, jakby wiedział, jakie są metody rozszerzenia.

1

Metody rozszerzeń nie będą działały w C# 2, ponieważ polegają na kompilatorze C# 3. C# 3 kompilator wie, jak to zrobić tłumaczenie z tego:

foo.Bar() 

do tego:

ExtensionClass.Bar(foo) 
22

Tagi powiedzenia .NET 2.0; Jeśli używasz języka C# 3.0 (tj. VS 2008) i targetowania .NET 2.0, możesz to zrobić, deklarując atrybut ExtensionAttribute - lub (łatwiej) tylko odwołując się do LINQBridge.

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

Dzięki temu na miejscu metody rozszerzeń będą działać w .NET 2.0 z C# 3.0.

2

Jak powiedział JS, C# 2.0 nie ma metod rozszerzenia.

Również ta metoda rozszerzenie byłoby zdefiniowane jako:

public static DataTable ToDataTable(this IDataReader reader) 

Spróbuj nazywając ją lubię:

DataReaderExtensions.ToDataTable(
    cust.GetCustomerOrderSummary((string)Session["CustomerNumber"]) 
    ) 
Powiązane problemy