在現代開發中,為減少單文件代碼量、降低協同開發時的文件鎖定衝突,C# 擴展方法 被廣泛使用。它允許在不創建派生類、不重新編譯原類型的情況下,「為現有類型添加」方法。本質上,擴展方法是特殊的靜態方法,但可像實例方法一樣調用。
隨著 DLR (Dynamic Language Runtime) 普及,C# 與腳本語言 (如 IronPython) 互操作需求增長。然而,DLR 預設無法識別 C# 擴展方法,直接調用會拋出 AttributeError。

雖可通過 import 導入 DLL 與類型定義,但 DLR 引擎無法識別擴展方法 Foo。
需使用 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# 擴展方法,實現無縫互操作。