vs2008中让基于.net 2.0的应用程序也可以使用扩展方法

本文介绍如何在.NET 2.0环境中利用扩展方法增强类库的功能,需使用.NET 3.5编译器并通过自定义扩展属性解决兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用过vs2008进行.net 3.0/3.5做过开发的都知道有一个很方面不修改现有代码的情况下扩展现有类库的编码方式-扩展方法;但使用他的前提是类库必须基于.net 3.0/3.5 framework。

namespace Tests
{
public static class ExtensionClass
{
public static void ToConsole(this string value)
{

System.Console.WriteLine(value);
}
}
class Program
{
static void Main()
{
string test = "Test String!";
test.ToConsole();
}
}
}

上面这段代码在vs2008中基于.net 2.0编译会报下面的编译错误

error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

编译告诉我们说找不到System.Runtime.CompilerServices.ExtensionAttribute,这个类在System.Core.dll中申明

无意之中,在网上找到一篇帖子:Using Extension Methods in .net 2.0

只要添加以下代码就可以使编译通过并运行,但是必须使用.net 3.5的编译器。

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

由于没有合适的测试环境,至于是不是可以在只安装了.net 2.0的机器上运行就没有做测试了,如果哪位dx做了测试,欢迎告知!

Technorati : 扩展方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值