English 中文(简体)
在 C# 2.0 中的扩展方法
原标题:
  • 时间:2009-04-01 20:09:48
  •  标签:

我需要哪个命名空间来使我的扩展程序工作?

这是我的扩展方法


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;
        }
    }
}

当我试图这样使用它时

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

它无法工作。这是 .net 2.0。

最佳回答

你不能这样做。C# 2.0 根本没有扩展方法。你可以按照我的“C#/.NET 版本”文章中所述,在 Visual Studio 2008 中 定位 .NET 2.0,使用 C# 3.0 的扩展方法,但你不能说服 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 { }
}

有了这个,扩展方法将在.NET 2.0和C# 3.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"])
   )




相关问题
热门标签