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

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.