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中申明
网上帖子:
只要添加以下代码就可以使编译通过并运行,但是必须使用.net 3.5的编译器。
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute { }
}