ObjectExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.ComponentModel;
  5. namespace Abp.Extensions
  6. {
  7. /// <summary>
  8. /// Extension methods for all objects.
  9. /// </summary>
  10. public static class ObjectExtensions
  11. {
  12. /// <summary>
  13. /// Used to simplify and beautify casting an object to a type.
  14. /// </summary>
  15. /// <typeparam name="T">Type to be casted</typeparam>
  16. /// <param name="obj">Object to cast</param>
  17. /// <returns>Casted object</returns>
  18. public static T As<T>(this object obj)
  19. where T : class
  20. {
  21. return (T)obj;
  22. }
  23. /// <summary>
  24. /// Converts given object to a value type using <see cref="Convert.ChangeType(object,System.TypeCode)"/> method.
  25. /// </summary>
  26. /// <param name="obj">Object to be converted</param>
  27. /// <typeparam name="T">Type of the target object</typeparam>
  28. /// <returns>Converted object</returns>
  29. public static T To<T>(this object obj)
  30. where T : struct
  31. {
  32. if (typeof(T) == typeof(Guid))
  33. {
  34. return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(obj.ToString());
  35. }
  36. return (T)Convert.ChangeType(obj, typeof(T), CultureInfo.InvariantCulture);
  37. }
  38. /// <summary>
  39. /// Check if an item is in a list.
  40. /// </summary>
  41. /// <param name="item">Item to check</param>
  42. /// <param name="list">List of items</param>
  43. /// <typeparam name="T">Type of the items</typeparam>
  44. public static bool IsIn<T>(this T item, params T[] list)
  45. {
  46. return list.Contains(item);
  47. }
  48. }
  49. }