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 - 博客园

转载于:https://www.cnblogs.com/crwy/p/10574782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值