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

后端 未结 7 815
灰色年华
灰色年华 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:28

    Here's a place where this would be useful. Say you have a strongly-typed OptionKey for declaring options.

    public static class DefaultOptions
    {
        public static OptionKey SomeBooleanOption { get; }
        public static OptionKey SomeIntegerOption { get; }
    }
    

    Where options are exposed through the IOptions interface:

    public interface IOptions
    {
        /* since options have a default value that can be returned if nothing's
         * been set for the key, it'd be nice to use the property instead of the
         * pair of methods.
         */
        T this[OptionKey key]
        {
            get;
            set;
        }
    
        T GetOptionValue(OptionKey key);
        void SetOptionValue(OptionKey key, T value);
    }
    

    Code could then use the generic indexer as a nice strongly-typed options store:

    void Foo()
    {
        IOptions o = ...;
        o[DefaultOptions.SomeBooleanOption] = true;
        int integerValue = o[DefaultOptions.SomeIntegerOption];
    }
    

提交回复
热议问题