0

I want to get field's information from some object but get stucked on retrieving data from nested class. GetFields() from recursive call return FieldInfo[0].

Here code sample.

 public class Test1
    {
        public string Name;
        public int Id;
        public object Value;
        public Test2 Test;
    }

    public class Test2
    {
        public float Value;
        public bool IsEnable;
    }

    class Program
    {
        static void Main()
        {
            var test1 = new Test1
                {
                    Name = "Test 1",
                    Id = 1,
                    Value = false,
                    Test = new Test2
                        {
                            Value = 123,
                            IsEnable = true,
                        },
                };

            GetTypeFields(test1);

            Console.ReadLine();
        }

        public static void GetTypeFields(object data)
        {
            var fields = data.GetType().GetFields();

            foreach (var fi in fields)
            {
                var type = fi.FieldType;

                if (type.IsValueType || type == typeof(string) || type == typeof(object))
                {
                    Console.WriteLine(fi.FieldType + " : " + fi.Name + " = " + fi.GetValue(data));
                }

                if (type.IsClass && type != typeof (string) && type != typeof(object))
                {
                    GetTypeFields(fi);
                }
            }
        }
    }

Could someone help with this?

4

1 回答 1

1

你很亲密。在第二次通话中,您需要拨打GetTypeFields(fi.GetValue(data)). 当前,您将FieldInfo对象提供给第二次调用,而不是实际的类对象。

于 2013-07-12T11:40:35.650 回答