代码改变世界

在C#环境中动态调用IronPython脚本(二)

2016-04-03 11:56  Dorisoy  阅读(888)  评论(0编辑  收藏  举报

一、Python数据类型与C#数据类型的对应

      Python中数据类型中的简单类型,例如int,float,string可以对应到C#环境中的int32,double,string,这些对应比较直观,Python中的复杂数据类型,例如List,Set等是C#环境中没有的,好在IronPython提供了这些数据类型的C#接口,使我们可以在C#环境中使用它们。如下表所示。

C#                                                                     Python      

IronPython.Runtime.SetCollection   ―――  Set

IronPython.Runtime.List                    ――――  List

IronPython.Runtime.PythonDictionary ―― Dictionary

(本文所列出的数据类型足够使用,作为研究,可以列出其他数据类型的对应,但实际编程无此必要。)

下图是SetCollection、List和PythonDictionary的继承关系图。

 

        笔者以为,这些接口类的作用是与Python“通信”,能够从这些封装体中取出或存入数据即可,这些数据的后处理或前处理宜采用C#环境中的“原生类”比较合适,而不要采用这些封装类中的一些特别的方法。因此这里列出这些封装类的一些基本方法(主要是存取数据方面的)。

[csharp] view plain copy
 
  1. SetCollection主要方法  
  2. SetCollection   copy ()  
  3. void    clear ()  
  4. IEnumerator< object >     GetEnumerator ()  
  5. int     Count  
  6.   
  7. IronPython.Runtime.List主要方法  
  8. int     index (object item)  
  9. int     index (object item, int start)  
  10. int     index (object item, int start, int stop)  
  11. void    insert (int index, object value)  
  12. void    Insert (int index, object value)  
  13. object  pop ()  
  14. object  pop (int index)  
  15. void    remove (object value)  
  16. void    reverse ()  
  17. void    RemoveAt (int index)  
  18. bool    Contains (object value)  
  19. void    Clear ()  
  20. int     IndexOf (object value)  
  21. int     Add (object value)  
  22. void    CopyTo (Array array, int index)  
  23. void    CopyTo (object[] array, int arrayIndex)  
  24. bool    Remove (object item)  
  25. int     Count  
  26.   
  27. PythonDictionary主要方法  
  28. void    Add (object key, object value)  
  29. bool    ContainsKey (object key)  
  30. bool    Remove (object key)  
  31. bool    TryGetValue (object key, out object value)  
  32. void    Add (KeyValuePair< object, object > item)  
  33. void    Clear ()  
  34. bool    Contains (KeyValuePair< object, object > item)  
  35. void    CopyTo (KeyValuePair< object, object >[] array, int arrayIndex)  
  36. int     Count  

这些方法与C#固有的集合类很类似,比较好用。

 

二、脚本错误处理

        动态脚本的运行,由于有用户参于的成份,因此出错的可能性很大,脚本的解析和运行,应该包含在一个大的Try…Catch中,应用程序不应该因为脚本的错误而中断,能够给出一个友好的、有意义的出错信息,是这类程序必须考虑的问题。

1.      如果脚本编写错误(语法错误),在执行对脚本执行Execute时,产生SyntaxErrorException。

2.      脚本中,如果没有找到类或方法,产生UnboundNameException,类中未定义方法,产生 MissingMemberException,方法传入参数个数错误,产生ArgumentTypeException, 传入参数类型不对,产生TypeErrorException

3.      如果脚本运行正确,在GetVariable时,变量名字写错了,会产生MissingMemberException。

4.      脚本中没有找到方法或类UnboundNameException, 类中未定义方法MissingMemberException。

以上只列出了脚本语法错误和调用错误,未包含运行错误(例如被零除),更详细的异常信息,请查阅Ironpython的帮助文档。