[英]Extension Method in C# 2.0
我需要什么命名空间才能让我的扩展工作
这是我的扩展方法
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 根本没有扩展方法。 You can use extension methods from C# 3.0 in Visual Studio 2008 targeting .NET 2.0 as described in my "C#/.NET versions" article but you can't persuade a C# 2.0 compiler to act as if it understands what extension methods are.
标签上写着 .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"])
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.