如何在IronPython中使用C#扩展方法

  在现在的开发过程中为了减少单个文件的代码量,降低协同开发时文件被独占锁定的几率,我们经常会使用扩展方法。扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

  随着DLR的广泛使用,面临越来越多需要C#代码和脚本语言交互的需求。(如果你知道如何使用,建议去DLR的官方网站去看看)但是,对于扩展方法来说如果直接使用会有发现DLR无法查找到指定的方法。

 

 Foo方法是一个扩展方法,虽然你可以不经雕琢的使用import方法导入你的DLL和类型定义,但是DLR引擎无法识别Foo方法,会引发AttributeError错误。为了解决这个问题,需要使用 Microsoft.Scripting.Runtime.ExtensionType扩展标识。

ContractedBlock.gif ExpandedBlockStart.gif Code
 1[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=true)]
 2public sealed class ExtensionTypeAttribute : Attribute
 3ExpandedBlockStart.gifContractedBlock.gif{
 4    // Fields
 5    private readonly Type _extends;
 6    private readonly Type _extensionType;
 7
 8    // Methods
 9    public ExtensionTypeAttribute(Type extends, Type extensionType)
10ExpandedSubBlockStart.gifContractedSubBlock.gif    {
11        if (extends == null)
12ExpandedSubBlockStart.gifContractedSubBlock.gif        {
13            throw new ArgumentNullException("extends");
14        }

15        if (((extensionType != null&& !extensionType.IsPublic) && !extensionType.IsNestedPublic)
16ExpandedSubBlockStart.gifContractedSubBlock.gif        {
17            throw Error.ExtensionMustBePublic(extensionType.FullName);
18        }

19        this._extends = extends;
20        this._extensionType = extensionType;
21    }

22
23    // Properties
24    public Type Extends
25ExpandedSubBlockStart.gifContractedSubBlock.gif    {
26        get
27ExpandedSubBlockStart.gifContractedSubBlock.gif        {
28            return this._extends;
29        }

30    }

31
32    public Type ExtensionType
33ExpandedSubBlockStart.gifContractedSubBlock.gif    {
34        get
35ExpandedSubBlockStart.gifContractedSubBlock.gif        {
36            return this._extensionType;
37        }

38    }

39}

40
41 
42

构造器 第一个参数是你扩展的目标类型,第二个参数是实现扩展方法的类。

 

 

转载于:https://www.cnblogs.com/DreamWinter/archive/2009/04/24/1443115.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值