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

后端 未结 6 1560
情书的邮戳
情书的邮戳 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:27

    The code posted to get the most-specific common base for a set of types has some issues. In particular, it breaks when I pass typeof(object) as one of the types. I believe the following is simpler and (better) correct.

    public static Type GetCommonBaseClass (params Type[] types)
    {
        if (types.Length == 0)
            return typeof(object);
    
        Type ret = types[0];
    
        for (int i = 1; i < types.Length; ++i)
        {
            if (types[i].IsAssignableFrom(ret))
                ret = types[i];
            else
            {
                // This will always terminate when ret == typeof(object)
                while (!ret.IsAssignableFrom(types[i]))
                    ret = ret.BaseType;
            }
        }
    
        return ret;
    }
    

    I also tested with:

    Type t = GetCommonBaseClass(typeof(OleDbCommand),
                                typeof(OdbcCommand),
                                typeof(SqlCommand));
    

    And got typeof(DbCommand). And with:

    Type t = GetCommonBaseClass(typeof(OleDbCommand),
                                typeof(OdbcCommand),
                                typeof(SqlCommand),
                                typeof(Component));
    

    And got typeof(Compoment). And with:

    Type t = GetCommonBaseClass(typeof(OleDbCommand),
                                typeof(OdbcCommand),
                                typeof(SqlCommand),
                                typeof(Component),
                                typeof(Component).BaseType);
    

    And got typeof(MarshalByRefObject). And with

    Type t = GetCommonBaseClass(typeof(OleDbCommand),
                                typeof(OdbcCommand),
                                typeof(SqlCommand),
                                typeof(Component),
                                typeof(Component).BaseType,
                                typeof(int));
    

    And got typeof(object).

提交回复
热议问题