您的位置:首页 > Web前端

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

2008-04-16 09:47 696 查看
使用过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 : 扩展方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐