2 using System.Collections.Generic;
10 public static class TypeExtensions
19 public static bool IsNumber(
this Type t)
21 return t == typeof(sbyte)
24 || t == typeof(ushort)
30 || t == typeof(
double)
31 || t == typeof(decimal);
38 public static List<PropertyInfo> GetXMLSerializableProperties(
this Type t)
40 return t.GetProperties().Where(PI => PI.IsXMLSerializeable()).ToList();
51 public static bool IsGenericList(
this Type type)
53 if (type == null)
return false;
55 foreach (Type
@interface in type.GetInterfaces())
57 if (
@interface.IsGenericType)
59 if (
@interface.GetGenericTypeDefinition() == typeof(ICollection<>))
77 public static bool IsGenericDictionary(
this Type type)
79 if (type == null)
return false;
81 foreach (Type
@interface in type.GetInterfaces())
83 if (
@interface.IsGenericType)
85 if (
@interface.GetGenericTypeDefinition() == typeof(IDictionary<,>))
101 public static Type[] GetGetGenericCollectionTypeArguments(
this Type type)
103 if (type == null)
return null;
104 if (!type.IsGenericList() && !type.IsGenericDictionary())
return null;
106 foreach (Type
@interface in type.GetInterfaces())
108 if (
@interface.IsGenericType)
110 if (
@interface.GetGenericTypeDefinition() == typeof(ICollection<>) |
@interface.GetGenericTypeDefinition() == typeof(IDictionary<,>))
113 return @interface.GetGenericArguments();
128 public static bool HasProperty(
this Type obj,
string PropertyName)
130 return obj.GetProperty(PropertyName) != null;
140 public static bool IsBuiltinType(
this Type type)
142 return type.Namespace ==
"System";
152 public static string GetFullName(
this Type t)
154 if (!t.IsGenericType)
156 StringBuilder sb =
new StringBuilder();
158 sb.Append(t.Name.Substring(0, t.Name.LastIndexOf(
"`")));
159 sb.Append(t.GetGenericArguments().Aggregate(
"<",
161 delegate(
string aggregate, Type type)
163 return aggregate + (aggregate ==
"<" ?
"" :
",") + GetFullName(type);
168 return sb.ToString();
172 public static string GetDisplayName(
this Type t)
174 if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
175 return string.Format(
"{0}?", GetDisplayName(t.GetGenericArguments()[0]));
177 return string.Format(
"{0}<{1}>",
178 t.Name.Remove(t.Name.IndexOf(
'`')),
179 string.Join(
",", t.GetGenericArguments().Select(at => at.GetDisplayName())));
181 return string.Format(
"{0}[{1}]",
182 GetDisplayName(t.GetElementType()),
183 new string(
',', t.GetArrayRank() - 1));