fork download
  1. using System;
  2. using static System.Console;
  3. using System.Reflection;
  4.  
  5. public class Program {
  6. public static void Main() {
  7. var teste = new Teste();
  8. teste.ListProperties();
  9. WriteLine(teste.GetPropValue<int>("y"));
  10. var teste2 = new Teste2();
  11. teste2.ListFields();
  12. }
  13. }
  14.  
  15. public class Teste {
  16. public int x { get; set; } = 10;
  17. public int y { get; set; } = 10;
  18. }
  19.  
  20. public class Teste2 {
  21. public int x = 10;
  22. public int y = 10;
  23. }
  24.  
  25. public static class ObjectExt {
  26. public static void ListProperties(this object obj) {
  27. foreach(var prop in obj.GetType().GetProperties()) {
  28. WriteLine($"{prop.Name} = {prop.GetValue(obj, null)}");
  29. }
  30. }
  31. public static void ListFields(this object obj) {
  32. foreach(var field in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
  33. WriteLine($"{field.Name} = {field.GetValue(obj)}");
  34. }
  35. }
  36. public static T GetPropValue<T>(this object value, string propertyName) {
  37. if (value == null) { throw new ArgumentNullException("value"); }
  38. if (String.IsNullOrEmpty(propertyName)) { throw new ArgumentException("propertyName"); }
  39. PropertyInfo info = value.GetType().GetProperty(propertyName);
  40. return (T)info.GetValue(value, null);
  41. }
  42. public static FieldInfo GetFieldInfo(this Type objType, string fieldName, BindingFlags flags, bool isFirstTypeChecked = true) {
  43. FieldInfo fieldInfo = objType.GetField(fieldName, flags);
  44. if (fieldInfo == null && objType.BaseType != null) fieldInfo = objType.BaseType.GetFieldInfo(fieldName, flags, false);
  45.  
  46. if (fieldInfo == null && isFirstTypeChecked) throw new MissingFieldException(String.Format("Field {0}.{1} could not be found with the following BindingFlags: {2}", objType.ReflectedType.FullName, fieldName, flags.ToString()));
  47. return fieldInfo;
  48. }
  49. }
  50.  
  51. //https://pt.stackoverflow.com/q/105236/101
Success #stdin #stdout 0.02s 16404KB
stdin
Standard input is empty
stdout
x = 10
y = 10
10
x = 10
y = 10