在C# 2.0版本中使用Extensions方法

在C# 2.0版本中使用Extensions方法

   最近在测试一个ftp类时发现其在.netcf V2版本下无法编译,但是却可以编译在3.0版本中。报错地方如下:

using System;
    using System.Runtime.CompilerServices;

    public static class Extensions
    {
        public static DateTime? ToDateTime(this WINAPI.FILETIME time)
        {
            if ((time.dwHighDateTime == 0) && (time.dwLowDateTime == 0))
            {
                return null;
            }
            uint dwLowDateTime = (uint)time.dwLowDateTime;
            long fileTime = (time.dwHighDateTime << 0x20) | dwLowDateTime;
            return new DateTime?(DateTime.FromFileTimeUtc(fileTime));
        }
    }

    后来经过查找资料了解到是.netcf V3.0版本中的Extension Method特性。Extension Method 的一个主要用途便是构造辅助方法。 

解决该问题可以使用以下两种方式:

方法一:在现有项目中添加System.core.dll的References。这样在编译时不会报错,并且经测试使用正常。但是每个项目中都会包含一个System.core.dll文件比较不爽。

方法二:在项目中添加以下代码:

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

添加该代码后编译不会报错,并且运行正常。也不用再添加那个.netcf V3.0的system.core.dll文件。

    在查资料过程中发现“善用 C# 3.0 Extensions 方法”这篇文章不错。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值