【问题标题】:Embedded IronPython scripts and converting types嵌入式 IronPython 脚本和转换类型
【发布时间】:2009-07-31 09:00:29
【问题描述】:

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

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

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

map.CanvasLocation = 10,10

这会出现一个异常,说它不能从 PythonTuple 转换为 System.Windows.Point。

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

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

【问题讨论】:

    标签: wpf ironpython embedding


    【解决方案1】:

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

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

    然后我用下面的代码在属性setter中找到转换器(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));
    }
    

    【讨论】:

      【解决方案2】:

      为什么不做一个

      map.CanvasLocation = Point(10,10)
      

      【讨论】:

      • 我能做到。这会起作用,但它也不是很用户友好。我想让脚本尽可能易于使用。
      猜你喜欢
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      相关资源
      最近更新 更多