Easiest way to get a common base class from a collection of types

后端 未结 6 1557
情书的邮戳
情书的邮戳 2020-12-17 05:07

I\'m building a custom property grid that displays the properties of items in a collection. What I want to do is show only the properties in the grid that are common amongst

6条回答
  •  悲&欢浪女
    2020-12-17 05:45

    I use something like this but Tony's answer is probably better:

    internal class BaseFinder
    {
        public static Type FindBase(params Type[] types)
        {
            if (types == null)
                return null;
    
            if (types.Length == 0)
                return null;
    
            Dictionary> baseTypeMap = new Dictionary>();
    
            // get all the base types and note the one with the longest base tree
            int maxBaseCount = 0;
            Type typeWithLongestBaseTree = null;
            foreach (Type type in types)
            {
                IList baseTypes = GetBaseTree(type);
                if (baseTypes.Count > maxBaseCount)
                {
                    typeWithLongestBaseTree = type;
                    maxBaseCount = baseTypes.Count;
                }
                baseTypeMap.Add(type, baseTypes);
            }
    
            // walk down the tree until we get to a common base type
            IList longestBaseTree = baseTypeMap[typeWithLongestBaseTree];
            for (int baseIndex = 0; baseIndex < longestBaseTree.Count;baseIndex++)
            {
                int commonBaseCount = 0;
                foreach (Type type in types)
                {
                    IList baseTypes = baseTypeMap[type];
                    if (!baseTypes.Contains(longestBaseTree[baseIndex]))
                        break;
                    commonBaseCount++;
                }
                if (commonBaseCount == types.Length)
                    return longestBaseTree[baseIndex];
            }
            return null;
        }
    
        private static IList GetBaseTree(Type type)
        {
            List result = new List();
            Type baseType = type.BaseType;
            do
            {
                result.Add(baseType);
                baseType = baseType.BaseType;
            } while (baseType != typeof(object));
            return result;
        }
    }
    

提交回复
热议问题