c#: .net framework 2.0支持扩展方法的办法

c#之扩展方法是个好方法,可惜只在.net framework 3.5及以上版本中用。

2.0版本若用,其编译报错如下:

错误    1    无法定义新的扩展方法,因为找不到编译器所需的类型“System.Runtime.CompilerServices.ExtensionAttribute”。是否缺少对 System.Core.dll 的引用?

那怎么办呢?

工程中加个文件,加其代码如下:

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

需要注意的是:若程序集中引用了Newtonsoft.Json.Net20.dll这个库,则可能会有如下错误:

缺少编译器要求的成员“System.Runtime.CompilerServices.ExtensionAttribute..ctor”

删除重引用就是了。

那么可以做扩展验证,比如给整型int加入一扩展方法,变为负数:

    public static class Utils
    {
        public static int ToNeg(this int v)
        {
            return -v;
        }
    }

即可做如下使用:

int i = 5;
Console.WriteLine(i.ToNeg());

的确是非常便捷。

参考资料:

c# - Using extension methods in .NET 2.0? - Stack Overflow

C# Extension methods in .NET 2.0 - Stack Overflow

c# - Extension Method in .net 2.0 in VS2008 - Stack Overflow

缺少编译器要求的成员“System.Runtime.CompilerServices.ExtensionAttribute..ctor” 解决方案 - ChineseMoonGod - 博客园

猜你喜欢

转载自www.cnblogs.com/crwy/p/10574782.html