Advertisement
Guest User

Untitled

a guest
Nov 21st, 2014
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. public interface IValidatable
  2. {
  3. bool IsValid { get; }
  4. void Validate();
  5. // (more validation-related methods here...)
  6. }
  7.  
  8. public class Validatable<T> : IValidatable
  9. where T : class
  10. {
  11. public Validatable(T obj)
  12. {
  13. Object = obj;
  14. }
  15.  
  16. public T Object { get; private set; }
  17.  
  18. public bool IsValid { get; set; }
  19.  
  20. public void Validate()
  21. {
  22.  
  23. }
  24.  
  25. public static implicit operator Validatable<T>(T other)
  26. {
  27. return new Validatable<T>(other);
  28. }
  29.  
  30. public static explicit operator T(Validatable<T> other)
  31. {
  32. return other.Object;
  33. }
  34.  
  35. }
  36.  
  37. public static class Validatable
  38. {
  39. public static IValidatable AsValidatable<T>(T obj)
  40. where T: class
  41. {
  42. if (obj == null)
  43. return null;
  44.  
  45. var already = obj as IValidatable;
  46.  
  47. return already ?? new Validatable<T>(obj);
  48. }
  49. }
  50.  
  51. public class Person // not IValidatable
  52. {
  53. public string FirstName { get; set; }
  54. public string LastName { get; set; }
  55. }
  56.  
  57. public void ConversionTest()
  58. {
  59. var person = new Person { FirstName = "Bob", LastName = "Smith" };
  60.  
  61. var validatable = Validatable.AsValidatable(person);
  62.  
  63. var cast = (Person)validatable; // FAILS here with InvalidCastException
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement