Get property of generic class

后端 未结 5 993
孤城傲影
孤城傲影 2020-12-03 09:26

I have a generic class, and an object value where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>).

class Foo
{
    publ         


        
5条回答
  •  星月不相逢
    2020-12-03 10:07

    Hey guys ive been struggeling with the same issue with generic typs and finally found the solution that gets the value --------Small code snippet of the method that does the trick ------------------

        public void printFields()
        {
            // Is the list empty
            if (this.list_.Count == 0)
            {
                //Y => Forced exit no object info
                return;
            }
    
            try
            {
                // Get first item from list
                T item = this.list_[0];
    
                // Get the type of object
                //**Type thisType = item.GetType();
    
                // Get array of all fields
                FieldInfo[] thisFieldInfo = item.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    
                // Loop through all fields and show its info
                for (int ix = 0; ix < thisFieldInfo.Length; ix++)
                {
                    // Get Field value
                    String strVal = thisFieldInfo[ix].GetValue(item).ToString();
    
                    // Display item
                    Console.WriteLine("'{0}' is a {1} and has value {2}", thisFieldInfo[ix].Name, thisFieldInfo[ix].FieldType, strVal);
                }
    
    
            }
            catch (SecurityException e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    

提交回复
热议问题