c# Reflection - Find the Generic Type of a Collection

前端 未结 3 1158
说谎
说谎 2021-02-18 14:43

I\'m reflecting a property \'Blah\' its Type is ICollection

    public ICollection Blah { get; set; }

    private void button1_Click(object sender         


        
3条回答
  •  时光取名叫无心
    2021-02-18 15:08

    I had a similar but much more complicated problem... I wanted to determine if a type is assignable to collection type members or array type members dynamically.

    So, here is better way how to get member type of collection or array dynamically with a validation if the type of an object to add is assignable to the collection or the array type members:

            List main = new List() { "str", "řetězec" };
            IComparable[] main0 = new IComparable[] { "str", "řetězec" };
            IEnumerable collection = (IEnumerable)main;
            //IEnumerable collection = (IEnumerable)main0;
            string str = (string) main[0];
            if (collection.GetType().IsArray)
            {
                if (collection.GetType().GetElementType().IsAssignableFrom(str.GetType()))
                {
                    MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
                }
                else
                {
                    MessageBox.Show("Bad Collection Member Type");
                }
            }
            else
            {
                if (collection.GetType().GenericTypeArguments[0].IsAssignableFrom(str.GetType()))
                {
                    MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
                }
                else
                {
                    MessageBox.Show("Bad Collection Member Type");
                }
            }
    

提交回复
热议问题