嵌入式 IronPython 脚本和转换类型

发布于 2024-07-29 23:38:19 字数 406 浏览 1 评论 0原文

我有一个嵌入 IronPython 用作脚本语言的 WPF 应用程序。 我有一个对象模型,IronPython 脚本可以用它来做“事情”。

然而,我遇到了一个奇怪的问题,我以一种我认为不正确的方式解决了这个问题。

在我的脚本中,我想输入以下内容来设置 WPF 中对象的位置。

map.CanvasLocation = 10,10

这会出现一个异常,表示它无法从 PythonTuple 转换为 System.Windows.Point。

我目前已经在我的 c# 对象中使用自定义类型转换器解决了这个问题,但我不确定这是否是最好的方法。

有没有办法告诉 IronPython 或 .Net 一般如何从一种类型转换为另一种可以在运行时扩展的类型?

I've got a WPF application that embeds IronPython to use as a scripting language. I've got an object model that IronPython scripts can use to do 'stuff'.

However I've come across a strange problem that I've solved in a way that I don't believe is correct.

In my script I want to type the following to set the location of an object in WPF.

map.CanvasLocation = 10,10

This comes up with an exception saying that it cannot convert from PythonTuple to System.Windows.Point.

I've currently solved that using a custom type converter in my c# object, but I'm not sure if this is the best way to do it.

Is there a way to tell IronPython or .Net in general how to convert from one type to another that can be extended at run time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

零時差 2024-08-05 23:38:23

为什么不做一个

map.CanvasLocation = Point(10,10)

Why not do a

map.CanvasLocation = Point(10,10)
捎一片雪花 2024-08-05 23:38:22

我这样做的方法是使用 TypeDescriptor 在运行时向 PythonTuple 添加类型转换器属性。

TypeDescriptor.AddAttributes(typeof(PythonTuple), 
    new TypeConverterAttribute(typeof(Converter)));

然后我使用以下代码在属性设置器中查找转换器(SetMemberAfter 方法)

var converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(destinationType))
{
    var destinationValue = converter.ConvertTo(value, destinationType);
    return destinationValue;
}
else
{
    throw new InvalidOperationException("Cannot convert from {0} to {1}".UIFormat(
        value == null ? "null" : value.GetType().Name, destinationType.Name));
}

The way I do this is to use TypeDescriptor to add a type converter attribute to PythonTuple at runtime.

TypeDescriptor.AddAttributes(typeof(PythonTuple), 
    new TypeConverterAttribute(typeof(Converter)));

Then I use the following code to find the converter in the attribute setter (SetMemberAfter method)

var converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(destinationType))
{
    var destinationValue = converter.ConvertTo(value, destinationType);
    return destinationValue;
}
else
{
    throw new InvalidOperationException("Cannot convert from {0} to {1}".UIFormat(
        value == null ? "null" : value.GetType().Name, destinationType.Name));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文