【问题标题】:How do I make a dynamic .Net object enumerable from IronRuby?如何使 IronRuby 中的动态 .Net 对象可枚举?
【发布时间】:2014-06-29 18:35:08
【问题描述】:

我有一个应用程序在 C# 中实现了多个对象,然后通过将这些对象添加到 Microsoft.Scripting.Hosting.ScriptScope 来期望这些对象可以从 IronRuby 中使用。这在大多数情况下都有效:我已经学会了如何实现 DynamicObject 的各种成员以使事情正确运行。但是如何使对象与 Ruby 的 for 循环兼容?

我的 C# 对象如下所示:

 public class TrialObject : DynamicObject, IEnumerable<int> {
    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
       if (indexes.Length != 1) return base.TryGetIndex(binder, indexes, out result);
       try {
          var index = (int)indexes[0];
          result = index;
          return true;
       } catch { return base.TryGetIndex(binder, indexes, out result); }
    }

    public int Length { get { return 3; } }

    public IEnumerator<int> GetEnumerator() {
       yield return 0;
       yield return 1;
       yield return 2;
    }

    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
 }

然后我尝试使用来自 ruby​​ 的对象,就像这样。

trial.Length                   # returns 3
trial[0]                       # returns 0
trial[2]                       # returns 2
for t in trial do <stuff>; end #error: no block given

如何调整 Trial 对象以使其在 for 循环中工作?我知道我可以使用“i in 0..trial.Length-1”作为破解,但我宁愿解决问题也不愿引入破解。

【问题讨论】:

    标签: c# .net foreach ironruby


    【解决方案1】:

    经过反复试验,我了解到可以通过在我的类中添加“each”方法来获得预期的效果。

    public class TrialObject : DynamicObject, IEnumerable<int> {
       ...
       public IEnumerable<BuildableObject> each() { return this; }
       ...
    }
    

    似乎 Ironruby 使用“each”方法来实现它的 for。因此,通过添加 each 方法,我可以让这个动态对象表现得像它试图成为的 IEnumerable。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-27
      • 2016-09-16
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2019-05-09
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多