I'm having trouble figuring out how to get Powershell to call an indexer on my class. The class looks something like this (vastly simplified):
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... } }
}
If I new up this class I can't just use the bracket operator on it - I get an "unable to index" error. I also tried using get_item(), which is what Reflector shows me the indexer ultimately becomes in the assembly, but that gets me a "doesn't contain a method named get_item" error.
UPDATE: this appears specific to my use of explicit interfaces. So my new question is: is there a way to get Powershell to see the indexer without switching away from explicit interfaces? (I really don't want to modify this assembly if possible.)
Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.
You can't make a Static Indexer in C#… The CLR can, but you can't with C#. You can't even trick the compiler with VB.NET.
“this” keyword is always used to declare an indexer. To define the value being assigned by the set indexer, ” value” keyword is used. Indexers are also known as the Smart Arrays or Parameterized Property in C#.
This works for me (uses reflection):
$obj = new-object MyClass
$p = [IIntCounters].GetProperty("Item")
$p.GetValue($obj, @("counterName"))
I haven't tried this, but it seems like it should work:
$obj = new-object MyClass
$counters = [IIntCounters]$obj
$counters['countername']
(OK, I played around a little and I no longer think this is likely to work, but it still may be worth a try.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With