代码之家  ›  专栏  ›  技术社区  ›  scobi

如何从PowerShell调用C类上的索引器?

  •  7
  • scobi  · 技术社区  · 15 年前

    我不知道如何让Powershell调用类中的索引器。这个类看起来像这样(大大简化了):

    public interface IIntCounters
    {
        int this[string counterName] { get; set; }
    }
    
    public class MyClass : IIntCounters
    {
        public IIntCounters Counters { get { return this; } }
    
        int IIntCounters.this[string counterName]
            { get { ...return something... } }
    }
    

    如果我更新了这个类,我不能只在它上面使用括号运算符-我得到一个“无法索引”错误。我还尝试使用get_item(),这是Reflector向我显示索引器最终在程序集中变成的内容,但这会导致“不包含名为get_item的方法”错误。

    这似乎是我使用显式接口所特有的。所以我的新问题是:有没有一种方法可以让Powershell在不脱离显式接口的情况下看到索引器?(如果可能,我真的不想修改此程序集。)

    2 回复  |  直到 15 年前
        1
  •  5
  •   dvdvorle    15 年前

    这对我有效(使用反射):

    $obj = new-object MyClass
    $p = [IIntCounters].GetProperty("Item")
    $p.GetValue($obj, @("counterName"))
    
        2
  •  2
  •   OldFart    15 年前

    我还没试过,但似乎应该管用:

    $obj = new-object MyClass
    $counters = [IIntCounters]$obj
    $counters['countername']