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))

  • 相关阅读:
    Linux里的2>&1究竟是什么
    表锁操作
    日志rsyslog
    计划任务at cron
    rpm包管理和源码包管理
    自建yum源(只演示nginx服务,其它都一样)
    软件包管理yum
    文件打包及压缩
    查找文件which locate find
    lsof恢复进程打开的文件
  • 原文地址:https://www.cnblogs.com/warensoft/p/IronPython.html
Copyright © 2011-2022 走看看