1

Closed

overriding indexer

description

A while ago there were the methods getitem and setitem which allowed to override an indexer.
I can't find these methods anymore and I also can't find a way to override an indexer.
 
namespace ClrModels {
 
public class IndexerContained{
 
    private Dictionary<string, string> _inner = new Dictionary<string, string>{
        { "key1", "value1" },
        { "key2", "value2" },
        { "key3", "value3" },
        { "key4", "value4" }
    };
 
    public virtual string this[string name]{
      get { return _inner[name]; }
      set { _inner[name] = value; }
    }
}
 
public class IndexerCaller{
 
    public string CallIndexOnClass(IndexerContained klass, string name){
        return klass[name];
    }
 
    public string CallIndexOnInterface(IHaveAnIndexer klass, string name){
        return klass[name];
    }
 
}
}
 
class MySubIndexer < ClrModels::IndexerContained;
def ; 6; end;
def Item(name); 7; end;
def item(name); 8; end;
def get_Item(name); 9; end;
end
 
cons = ClrModels::IndexerCaller.new
=> ClrModels.IndexerCaller
cons.call_index_on_class(MySubIndexer.new, "key")
unknown:0: warning: do not use Fixnums as Symbols
=> 'Fail'
 
 
And a spec to go with it:
 
require File.dirname(FILE) + "/../spec_helper"
 
describe "CLR to CLR interactions" do
 
describe "when isolating CLR classes" do
 
describe "that have an indexer" do
  before do
    @cons = ClrModels::IndexerCaller.new
    @ind = Caricature::Isolation.for(ClrModels::IndexerContained)
  end
 
  it "should work without expectations" do
    @cons.call_index_on_class(@ind, "key1").should.be.nil
  end
 
  it "should work with an expectation" do
    @ind.when_receiving(:__getitem__).return("5")

    @cons.call_index_on_class(@ind, "key1").should.equal "5"
  end
 
 
end
 
end
 
end
Closed Jul 28, 2011 at 12:23 AM by jimmysch
Fix provided

comments

TomasMatousek wrote Mar 9, 2010 at 12:48 AM

This works:

class MySubIndexer < ClrModels::IndexerContained;
def [](name); '6'; end; 
end

cons = ClrModels::IndexerCaller.new
p cons.call_index_on_class(MySubIndexer.new, "key1")