IronPython for C#(四)
如何将一个实例对象或者单独一个方法传递到python代码中呢???
class MyClass:
i = 123
__name = "NB"
fo = None
def __init__(self, num):
self.i = num
def h(self):
return "Hello"
def f(self):
return self.fo(3)
def tostr(self):
return self.p.Name + self.p.ToString()
- 可以利用委托将一个方法赋给python中的一个变量
- 可以将一个类实例赋给python的一个变量,在python中该变量就可以访问该实例中的属性和方法
- python中如果要访问实例中的属性,必须将该属性的访问符和所有相关的类访问符都设置为public
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime.Types;
public class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
dynamic oldInstance = scope.MyClass(56); //带参数的构造函数
dynamic res = oldInstance.h();
oldInstance.i = 45;
oldInstance.fo = new Func<int, int>(Get);
People p = new People() { Name = "BT" };
oldInstance.p = p;
dynamic i = oldInstance.i;
dynamic num = oldInstance.f();
dynamic str = oldInstance.tostr();
}
public class People
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
static int Get(int a)
{
return a;
}
}