您的位置:首页 > 编程语言 > C#

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

2011-09-06 18:29 375 查看
在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
方法”这篇文章不错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐