Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
  2. class DontSendInPublicApiAttribute : Attribute { }
  3.  
  4. public static void RemoveSecretData(object obj)
  5. {
  6. // Retrieve all public instance properties defined for the object's type and marked with [DontSendInPublicApi]
  7. var propertiesToHide = obj.GetType()
  8. .GetProperties(BindingFlags.Instance | BindingFlags.Public)
  9. .Where(p => p.GetCustomAttribute<DontSendInPublicApiAttribute>() != null);
  10.  
  11. foreach (var prop in propertiesToHide)
  12. {
  13. // Set all of these properties in the given object to their default values.
  14. // VALUE TYPES (ints, chars, doubles, etc.) will be set to default(TheTypeOfValue), by calling Activator.CreateInstance(TheTypeOfValue).
  15. // REFERENCE TYPES will simply be set to null.
  16. var propertyType = prop.PropertyType;
  17. if (propertyType.IsValueType)
  18. prop.SetValue(obj, Activator.CreateInstance(prop.PropertyType));
  19. else
  20. prop.SetValue(obj, null);
  21. }
  22. }
  23.  
  24. class Person
  25. {
  26. public string Name { get; set; }
  27. public int Age { get; set; }
  28.  
  29. [DontSendInPublicApi]
  30. public string Occupation { get; set; }
  31. [DontSendInPublicApi]
  32. public int Salary { get; set; }
  33. }
  34.  
  35. var person = new Person() { Name = "John", Age = 29, Occupation = "Engineer", Salary = 200000 };
  36. RemoveSecretData(person);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement