在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
方法”這篇文章不錯。