如何从 C# 获取 DLR 表示形式?
是否有将动态语言运行时 (DLR) 对象转换为字符串表示形式的通用方法? 几种特定类型(在本例中为 Python):
if (obj is IronPython.Runtime.List) {
repr = ((IronPython.Runtime.List)obj).__repr__(
IronPython.Runtime.DefaultContext.Default);
} else if (obj is IronPython.Runtime.PythonDictionary) {
repr = ((IronPython.Runtime.PythonDictionary)obj).__repr__(
IronPython.Runtime.DefaultContext.Default);
例如,下面是一个示例,其中检查 obj的 与每种类型进行比较。 obj.ToString() 不能很好地表示大多数对象。
Is there a generic method of converting a Dynamic Language Runtime (DLR) object into a string representation? For example, here is an example where obj is checked for a couple of specific types (Python, in this case):
if (obj is IronPython.Runtime.List) {
repr = ((IronPython.Runtime.List)obj).__repr__(
IronPython.Runtime.DefaultContext.Default);
} else if (obj is IronPython.Runtime.PythonDictionary) {
repr = ((IronPython.Runtime.PythonDictionary)obj).__repr__(
IronPython.Runtime.DefaultContext.Default);
But I would really like to get a representation of obj in its own language (IronPython, IronRuby, etc) and without having to compare to each and every type. obj.ToString() doesn't give a good representation for most objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AFAIK,没有一种通用方法可以将 DLR 对象转换为其代表性字符串表示形式。它依赖于语言,不幸的是它们的实现方式并不相同。
至少使用 IronPython,您始终可以获取对内置模块的引用,然后在对象上调用
str()
(或repr()
)函数。当然,您也可以在脚本中调用该函数。
另一种选择是使用 IronPython.Runtime.Operations 命名空间中定义的众多操作之一。
我对 IronRuby 不太熟悉,但在某些对象上调用
to_s()
有时似乎有效。否则,它实际上返回一个 .NET 对象,其中to_s
不存在并且不太可靠。我认为在脚本中完成它更容易。您可能想环顾四周,看看是否还有其他可以使用的方法。
AFAIK, there's no one common method to convert DLR objects to their representative string representations. It is language dependent and they are not implemented the same unfortunately.
With IronPython at least, you could always just get a reference to the Builtin module then call the
str()
(orrepr()
) function on your objects.Of course you could call the function within the script too.
Another option would be to use one of the many operations defined in the
IronPython.Runtime.Operations
namespace.I'm not very familiar with IronRuby but calling
to_s()
on some objects seems to work sometimes. Otherwise, it actually returns a .NET object whereto_s
does not exist and is not very reliable. I think it's easier to do it within the script.You might want to look around and see if there are other methods you could use.