zoukankan      html  css  js  c++  java
  • 利用IronPython实现.NET接口

    利用IronPython实现.NET接口

     

    在IronPython2.6中新增加了clrtype功能,这样我们就可以在IronPython中实现接口以及特性类的功能。

    要想使用clrtype,需要先引入clrtype.py这个文件,在安装完IronPython之后,我并没有在安装目录下发现这个文件,但是在IronPython2.6的Samples里找到了这个文件,Copy过来就OK了。

    先定义一个C#的接口,然后将其改写为Python的,代码如下:

    using System;

    public interface IMyInterface

        {

            string SayAge(int age);

        }

        public class MyClass:IMyInterface

        {

            public string SayAge(int age)

            {

                return "hello " + age.ToString();

            }

        }

    对就的Python程序如下所示:

    # coding=gb2312

    import clr

    import clrtype

    from System import *

    class IMyInterface(object):

        __metaclass__ = clrtype.ClrInterface#声明该类为接口类型

        _clrnamespace = "TestPython" #添加命名空间

        @clrtype.accepts(int)

        @clrtype.returns(str)

        def SayAge(self, age):

            raise RuntimeError("this should not get called")

    class MyClass(IMyInterface):

        __metaclass__ = clrtype.ClrClass#声明该类为类

        _clrnamespace = "TestPython"#添加命名空间

        def SayAge(self, age):

            return "hello " + str(age)

    mc = MyClass()

    Console.Write(mc.SayAge(10))

  • 相关阅读:
    java 环境变量配置
    框架分成介绍
    Net 新特性
    一 设计模式六大原则
    web api 配置
    Visual Studio检查内存泄露方法
    深度比较对象的不同
    reportview 安装使用
    Nuget 常用命令
    freeswitch学习笔记
  • 原文地址:https://www.cnblogs.com/warensoft/p/IronPython.html
Copyright © 2011-2022 走看看