我无法弄清楚如何让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在不切换显式接口的情况下看到索引器? (如果可能的话,我真的不想修改这个程序集。)
答案 0 :(得分:4)
这对我有用(使用反射):
$obj = new-object MyClass
$p = [IIntCounters].GetProperty("Item")
$p.GetValue($obj, @("counterName"))
答案 1 :(得分:2)
我没试过这个,但似乎它应该有用:
$obj = new-object MyClass
$counters = [IIntCounters]$obj
$counters['countername']
(好吧,我玩了一下,我不再认为这可能会起作用,但它仍然值得一试。)