I'm trying to do it like this, but it doesn't work out for me.

string data = ""; foreach (var prop in экземплярКласса.GetType().GetProperties()) { data += String.Format("{0}={1}{2}", prop.Name, prop.GetValue(экземплярКласса, null), Environment.NewLine); } Console.WriteLine(data); 

2 answers 2

 MyClass myInstance = new MyClass(); FieldInfo[] fields = myInstance.GetType().GetFields(); // или FieldInfo[] fields = myInstance.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for(int i = 0; i < fields .Length; i++) { Console.WriteLine("The value of {0} is: {1}", myFields[i].Name, fields [i].GetValue(myInstance)); } 

    If you are using .NET 4.5 or higher, it is more convenient to use the new Reflection API, represented by the TypeInfo class:

     IEnumerable<FieldInfo> fields = yourInstance.GetType().GetTypeInfo().DeclaredFields; foreach (var field in fields.Where(x => !x.IsStatic)) { Console.WriteLine("{0}={1}", field.Name, field.GetValue(yourInstance)); }