如何在IronPython中使用C#擴充方法

來源:互聯網
上載者:User

  在現在的開發過程中為了減少單個檔案的代碼量,降低協同開發時檔案被獨佔鎖定的幾率,我們經常會使用擴充方法。擴充方法使您能夠向現有類型“添加”方法,而無需建立新的衍生類別型、重新編譯或以其他方式修改原始類型。擴充方法是一種特殊的靜態方法,但可以像擴充類型上的執行個體方法一樣進行調用。

  隨著DLR的廣泛使用,面臨越來越多需要C#代碼和指令碼語言互動的需求。(如果你知道如何使用,建議去DLR的官方網站去看看)但是,對於擴充方法來說如果直接使用會有發現DLR無法尋找到指定的方法。

 

 Foo方法是一個擴充方法,雖然你可以不經雕琢的使用import方法匯入你的DLL和類型定義,但是DLR引擎無法識別Foo方法,會引發AttributeError錯誤。為瞭解決這個問題,需要使用 Microsoft.Scripting.Runtime.ExtensionType擴充標識。

Code
 1[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=true)]
 2public sealed class ExtensionTypeAttribute : Attribute
 3{
 4    // Fields
 5    private readonly Type _extends;
 6    private readonly Type _extensionType;
 7
 8    // Methods
 9    public ExtensionTypeAttribute(Type extends, Type extensionType)
10    {
11        if (extends == null)
12        {
13            throw new ArgumentNullException("extends");
14        }
15        if (((extensionType != null) && !extensionType.IsPublic) && !extensionType.IsNestedPublic)
16        {
17            throw Error.ExtensionMustBePublic(extensionType.FullName);
18        }
19        this._extends = extends;
20        this._extensionType = extensionType;
21    }
22
23    // Properties
24    public Type Extends
25    {
26        get
27        {
28            return this._extends;
29        }
30    }
31
32    public Type ExtensionType
33    {
34        get
35        {
36            return this._extensionType;
37        }
38    }
39}
40
41 
42

構造器 第一個參數是你擴充的目標類型,第二個參數是實現擴充方法的類。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.