作者:云崽美不美_525 | 来源:互联网 | 2023-05-18 04:36
class PythonProducts
{
static void Main()
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.ExecuteFile(@"CSharp4\FindProducts.py");
dynamic products = scope.GetVariable("products");
foreach (dynamic product in products)
{
Console.WriteLine("{0}: {1}", product.ProductName, product.Price);
}
}
}
假设 数据没有在 内存 数据库 xml文件 数据在 web服务中,访问通过python来。 python用动态特性来构建结果
dynamic 新的类型,如果为dynamic 类型的数据,可以调用其方法,访问其属性,作为方法的参数进行传递。
可将dynamic 转换 隐形转换为其他类型 在编译时找不出错误, 在运行是会找出错误
输入
FindProducts.py
class WebServiceResult(object): pass
# Imagine these are loaded dynamically...
product1 = WebServiceResult()
product1.ProductName = "West Wide Story"
product1.Price = 9.99
product2 = WebServiceResult()
product2.ProductName = "Assassins"
product2.Price = 14.99
products = [product1, product2]
输出
West Wide Story: 9.99
Assassins: 14.99
Console.WriteLine("{0}: {1}", product.ProductName, product.Price);
改成
Console.WriteLine("{0}: {1}", product.ProductName1, product.Price);
编译时不出错, 运行时出错
运行时有异常
Exception: System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: “IronPython.NewTypes.System.Object_1$1”未包含“ProductName1”的定义
在 CallSite.Target(Closure , CallSite , Object )
在 System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
在 C01.CSharp4.PythonProducts.Main() 位置 c:\Users\Adminstrator\Desktop\深入理解C# 第三版 源代码 - 副本\代码\Chapter01\CSharp4\PythonProducts.cs:行号 19
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
在 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
在 MiscUtil.ApplicationChooser.Run(Type type, String[] args)