我正在尝试使用嵌入式 IronPython 脚本编写 C# 代码。然后要分析脚本的内容,即列出所有变量、函数、类及其成员/方法。
假设我已经定义了一个范围并且已经在其中执行了代码,那么有一个简单的方法可以开始:
dynamic variables=pyScope.GetVariables();
foreach (string v in variables)
{
dynamic dynamicV=pyScope.GetVariable(); /*seems to return everything. variables, functions, classes, instances of classes*/
}
但是我如何弄清楚变量的类型是什么?对于以下 python '对象',
dynamicV.GetType()
将返回不同的值:
x=5 --system.Int32
y="asdf" --system.String
def func():... --IronPython.Runtime.PythonFunction
z=class() -- IronPython.Runtime.Types.OldInstance,我如何识别真正的 python 类是什么?
class NewClass -- 抛出错误,GetType() 不可用。
这几乎就是我要找的。我可以捕获不可用时抛出的异常并假设它是一个类声明,但这似乎不干净。有更好的方法吗?
要发现一个类的成员/方法,我可以使用:
ObjectOperations op = pyEngine.Operations;
object instance = op.Call("className");
foreach (string j in op.GetMemberNames("className"))
{
object member=op.GetMember(instance, j);
Console.WriteLine(member.GetType());
/*once again, GetType() provides some info about the type of the member, but returns null sometimes*/
}
另外,如何获取方法的参数?
谢谢!