ExpressionUtil.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Reflection;
  5. namespace System.Linq.Expressions
  6. {
  7. static class ExpressionUtil
  8. {
  9. public static bool IsNumber(Type type)
  10. {
  11. // enum can also be in a numeric form, but we
  12. // want it to be considered as a number?
  13. if (type.IsEnum)
  14. return false;
  15. TypeCode typeCode = Type.GetTypeCode(type);
  16. if (typeCode == TypeCode.Byte ||
  17. typeCode == TypeCode.Decimal ||
  18. typeCode == TypeCode.Double ||
  19. typeCode == TypeCode.Int16 ||
  20. typeCode == TypeCode.Int32 ||
  21. typeCode == TypeCode.Int64 ||
  22. typeCode == TypeCode.Single)
  23. return true;
  24. return false;
  25. }
  26. public static bool IsNumber(object value)
  27. {
  28. if (value == null)
  29. return false;
  30. return IsNumber(value.GetType());
  31. }
  32. /// <summary>
  33. /// tries to find the method with the given name in one of the
  34. /// given types in the array.
  35. /// </summary>
  36. /// <param name="methodName">The name of the method to find.</param>
  37. /// <param name="types">An array of <see cref="Type"/> (typically 2) defining
  38. /// the types we're going to check for the method.</param>
  39. /// <returns></returns>
  40. public static MethodInfo GetMethod(string methodName, Type[] types)
  41. {
  42. if (types.Length > 2)
  43. throw new ArgumentException();
  44. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  45. // the method should have the two types defined as argument...
  46. MethodInfo method = types[0].GetMethod(methodName, flags, null, types, null);
  47. if (method == null && types.Length > 1)
  48. method = types[1].GetMethod(methodName, flags, null, types, null);
  49. return method;
  50. }
  51. public static ReadOnlyCollection<MemberBinding> GetReadOnlyCollection(IEnumerable<MemberBinding> en)
  52. {
  53. if (en == null)
  54. return new ReadOnlyCollection<MemberBinding>(new MemberBinding[0]);
  55. List<MemberBinding> list = new List<MemberBinding>(en);
  56. return new ReadOnlyCollection<MemberBinding>(list);
  57. }
  58. public static ReadOnlyCollection<Expression> GetReadOnlyCollection(IEnumerable<Expression> en)
  59. {
  60. if (en == null)
  61. return new ReadOnlyCollection<Expression>(new Expression[0]);
  62. List<Expression> list = new List<Expression>(en);
  63. return new ReadOnlyCollection<Expression>(list);
  64. }
  65. }
  66. }