Why it is not possible to define generic indexers in .NET?

后端 未结 7 814
灰色年华
灰色年华 2020-12-05 12:31

Why can\'t you create a generic indexer in .NET?

the following code throws a compiler error:

   public T this[string key]
   {
      get { /         


        
7条回答
  •  心在旅途
    2020-12-05 13:19

    I like the ability to have an indexer without handing out a direct reference to the "indexed" item. I wrote a simple "call back" Indexer class below ...

    R = the returned type from the indexer P = the passed type into the indexer

    All the indexer really does is pass the operations to the deployer and allow them to manage what actually occurs and gets returned.

    public class GeneralIndexer
        {
            // Delegates
            public delegate R gen_get(P parm);
            public delegate void gen_set(P parm, R value);
            public delegate P[] key_get();
    
            // Events
            public event gen_get GetEvent;
            public event gen_set SetEvent;
            public event key_get KeyRequest;
    
            public R this[P parm]
            {
                get { return GetEvent.Invoke(parm); }
                set { SetEvent.Invoke(parm, value); }
            }
    
            public P[] Keys
            {
                get
                {
                    return KeyRequest.Invoke();
                }
            }
    
        }
    

    To use it in a program or class:

    private GeneralIndexer TimeIndex = new GeneralIndexer();
    
    {
                TimeIndex.GetEvent += new GeneralIndexer.gen_get(TimeIndex_GetEvent);
                TimeIndex.SetEvent += new GeneralIndexer.gen_set(TimeIndex_SetEvent);
                TimeIndex.KeyRequest += new GeneralIndexer.key_get(TimeIndex_KeyRequest);
    
    }
    

    works like a champ especially if you want to monitor access to your list or do any special operations when something is accessed.

提交回复
热议问题