我在 Ironpython 脚本中定义了字典,我想从我的 C# 访问该字典
代码。有人可以提供示例代码来实现我的要求。
抱歉,之前我没有用代码提及我的问题陈述。
import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)
from System.Collections.Generic import Dictionary,List
def check(self):
dict1 = Dictionary[str,str]
dict1["a"] = "aa"
dict2 = Dictionary[str,str]
dict2["b"] = "bb"
self[0] = dict1
# self.Add(dict1)
return self
C#
var runtime = Python.CreateRuntime();
dynamic test = runtime.UseFile("Test.py");
var myDictList = new List<Dictionary<string, string>>();
var myDL = new List<Dictionary<string, string>>();
myDL = test.check(myDictList);
我的目标是在 python 中的字典列表上进行操作(添加、从列表中删除)并将其发送回 C#,在那里我可以进一步使用它。
我想要的是在 python 或 C# 中创建一个字典列表,并在两个地方(python 和 C#)使用它。
我该怎么办呢。
这有效:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronPython;
using IronPython.Hosting;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ScriptEngine pyEngine = Python.CreateEngine();
ScriptScope pyScope = pyEngine.CreateScope();
ScriptSource pyScript = pyEngine.CreateScriptSourceFromString("d = {'a':1,'b':2,'c':3}");
CompiledCode pyCompiled = pyScript.Compile();
pyCompiled.Execute(pyScope);
IronPython.Runtime.PythonDictionary d = pyScope.GetVariable("d");
Console.WriteLine(d.get("a"));
Console.Read();
}
}
}
应该为您提供键“a”的第一个值。希望这能让你继续前进。
可能有一两个包含太多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)