Can I Create a Dictionary of Generic Types?

前端 未结 10 2445
误落风尘
误落风尘 2020-11-30 02:53

I\'d like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:

Dict         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 03:31

    We're using lots of reflection to create an extensible administration tool. We needed a way to register items in the global search in the module definition. Each search would return results in a consistent way, but each one had different dependencies. Here's an example of us registering search for a single module:

    public void ConfigureSearch(ISearchConfiguration config)
        {
            config.AddGlobalSearchCallback((query, ctx) =>
            {
                return ctx.Positions.Where(p => p.Name.Contains(query)).ToList().Select(p =>
                    new SearchResult("Positions", p.Name, p.ThumbnailUrl,
                        new UrlContext("edit", "position", new RouteValueDictionary(new { Id = p.Id }))
                        ));
            });
        }
    

    In the background during module registration, we iterate over every module and add the Func to a SearchTable with an instance of:

    public class GenericFuncCollection : IEnumerable>
    {
        private List> objects = new List>();
    
        /// 
        /// Stores a list of Func of T where T is unknown at compile time.
        /// 
        /// Type of T
        /// Type of the Func
        /// Instance of the Func
        public void Add(Object func)
        {
            objects.Add(new Tuple(typeof(T1), typeof(T2), func));
        }
    
        public IEnumerator> GetEnumerator()
        {
            return objects.GetEnumerator();
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return objects.GetEnumerator();
        }
    }
    

    Then when we finally call it, we do it with reflection:

    var dependency = DependencyResolver.Current.GetService(search.Item1);
    var methodInfo = search.Item2.GetMethod("Invoke");
    return (IEnumerable)methodInfo.Invoke(search.Item3, new Object[] { query, dependency });
    

提交回复
热议问题