首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

IronPython 中調用 C# 擴展方法:使用 ExtensionTypeAttribute 解決 DLR 識別問題

     編輯:關於C#

在現代開發中,為減少單文件代碼量、降低協同開發時的文件鎖定衝突,C# 擴展方法 被廣泛使用。它允許在不創建派生類、不重新編譯原類型的情況下,「為現有類型添加」方法。本質上,擴展方法是特殊的靜態方法,但可像實例方法一樣調用。

隨著 DLR (Dynamic Language Runtime) 普及,C# 與腳本語言 (如 IronPython) 互操作需求增長。然而,DLR 預設無法識別 C# 擴展方法,直接調用會拋出 AttributeError。

問題示例

DLR無法識別擴展方法Foo

雖可通過 import 導入 DLL 與類型定義,但 DLR 引擎無法識別擴展方法 Foo。

解決方案:ExtensionTypeAttribute

需使用 Microsoft.Scripting.Runtime.ExtensionTypeAttribute 標記程序集,讓 DLR 知曉擴展關係。

[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=true)]
public sealed class ExtensionTypeAttribute : Attribute
{
    private readonly Type _extends;
    private readonly Type _extensionType;

    public ExtensionTypeAttribute(Type extends, Type extensionType)
    {
        if (extends == null) throw new ArgumentNullException("extends");
        if (extensionType != null && !extensionType.IsPublic && !extensionType.IsNestedPublic)
            throw Error.ExtensionMustBePublic(extensionType.FullName);

        this._extends = extends;
        this._extensionType = extensionType;
    }

    public Type Extends { get { return this._extends; } }
    public Type ExtensionType { get { return this._extensionType; } }
}

構造函數參數說明:

  • extends:被擴展的目標類型 (如 typeof(string))。
  • extensionType:包含擴展方法的靜態類 (如 typeof(MyExtensions))。

在程序集層級 (通常在 AssemblyInfo.cs) 應用此特性:

[assembly: ExtensionTypeAttribute(typeof(string), typeof(MyNamespace.StringExtensions))]

如此,IronPython 等 DLR 語言即可正確識別並調用 C# 擴展方法,實現無縫互操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved