comparison Chronosv2/source/Extensions/ObjectExtensions.cs @ 10:443821e55f06

Initial cleaned up add from Codeplex files
author stevenh7776 stevenhollidge@hotmail.com
date Tue, 21 Feb 2012 17:25:44 +0700
parents
children
comparison
equal deleted inserted replaced
9:904a9faadf8b 10:443821e55f06
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4
5 namespace Chronos.Extensions
6 {
7 /// <summary>
8 /// Extension methods for the root data type object
9 /// </summary>
10 public static class ObjectExtensions
11 {
12 #region · Extensions ·
13
14 /// <summary>
15 /// Determines whether the object is equal to any of the provided values.
16 /// </summary>
17 /// <typeparam name="T"></typeparam>
18 /// <param name="obj">The object to be compared.</param>
19 /// <param name="values">The values to compare with the object.</param>
20 /// <returns></returns>
21 public static bool EqualsAny<T>(this T obj, params T[] values)
22 {
23 return (Array.IndexOf(values, obj) != -1);
24 }
25
26 /// <summary>
27 /// Determines whether the object is equal to none of the provided values.
28 /// </summary>
29 /// <typeparam name="T"></typeparam>
30 /// <param name="obj">The object to be compared.</param>
31 /// <param name="values">The values to compare with the object.</param>
32 /// <returns></returns>
33 public static bool EqualsNone<T>(this T obj, params T[] values)
34 {
35 return (obj.EqualsAny(values) == false);
36 }
37
38 /// <summary>
39 /// Converts an object to the specified target type or returns the default value.
40 /// </summary>
41 /// <typeparam name="T"></typeparam>
42 /// <param name="value">The value.</param>
43 /// <returns>The target type</returns>
44 public static T ConvertTo<T>(this object value)
45 {
46 return value.ConvertTo(default(T));
47 }
48
49 /// <summary>
50 /// Converts an object to the specified target type or returns the default value.
51 /// </summary>
52 /// <typeparam name="T"></typeparam>
53 /// <param name="value">The value.</param>
54 /// <param name="defaultValue">The default value.</param>
55 /// <returns>The target type</returns>
56 public static T ConvertTo<T>(this object value, T defaultValue)
57 {
58 if (value != null)
59 {
60 var targetType = typeof(T);
61
62 var converter = TypeDescriptor.GetConverter(value);
63
64 if (converter != null)
65 {
66 if (converter.CanConvertTo(targetType))
67 {
68 return (T)converter.ConvertTo(value, targetType);
69 }
70 }
71
72 converter = TypeDescriptor.GetConverter(targetType);
73
74 if (converter != null)
75 {
76 if (converter.CanConvertFrom(value.GetType()))
77 {
78 return (T)converter.ConvertFrom(value);
79 }
80 }
81 }
82
83 return defaultValue;
84 }
85
86 /// <summary>
87 /// Converts an object to the specified target type or returns the default value. Any exceptions are optionally ignored.
88 /// </summary>
89 /// <typeparam name="T"></typeparam>
90 /// <param name="value">The value.</param>
91 /// <param name="defaultValue">The default value.</param>
92 /// <param name="ignoreException">if set to <c>true</c> ignore any exception.</param>
93 /// <returns>The target type</returns>
94 public static T ConvertTo<T>(this object value, T defaultValue, bool ignoreException)
95 {
96 if (ignoreException)
97 {
98 try
99 {
100 return value.ConvertTo<T>();
101 }
102 catch
103 {
104 return defaultValue;
105 }
106 }
107
108 return value.ConvertTo<T>();
109 }
110
111 /// <summary>
112 /// Determines whether the value can (in theory) be converted to the specified target type.
113 /// </summary>
114 /// <typeparam name="T"></typeparam>
115 /// <param name="value">The value.</param>
116 /// <returns>
117 /// <c>true</c> if this instance can be convert to the specified target type; otherwise, <c>false</c>.
118 /// </returns>
119 public static bool CanConvertTo<T>(this object value)
120 {
121 if (value != null)
122 {
123 var targetType = typeof(T);
124
125 var converter = TypeDescriptor.GetConverter(value);
126
127 if (converter != null)
128 {
129 if (converter.CanConvertTo(targetType))
130 {
131 return true;
132 }
133 }
134
135 converter = TypeDescriptor.GetConverter(targetType);
136
137 if (converter != null)
138 {
139 if (converter.CanConvertFrom(value.GetType()))
140 {
141 return true;
142 }
143 }
144 }
145 return false;
146 }
147
148 /// <summary>
149 /// Converts the specified value to a different type.
150 /// </summary>
151 /// <typeparam name="T"></typeparam>
152 /// <param name="value">The value.</param>
153 /// <returns>An universal converter suppliying additional target conversion methods</returns>
154 /// <example><code>
155 /// var value = "123";
156 /// var numeric = value.Convert().ToInt32();
157 /// </code></example>
158 public static IConverter<T> Convert<T>(this T value)
159 {
160 return new Converter<T>(value);
161 }
162
163 /// <summary>
164 /// Dynamically invokes a method using reflection
165 /// </summary>
166 /// <param name="obj">The object to perform on.</param>
167 /// <param name="methodName">The name of the method.</param>
168 /// <param name="parameters">The parameters passed to the method.</param>
169 /// <returns>The return value</returns>
170 /// <example>
171 /// <code>
172 /// var type = Type.GetType("System.IO.FileInfo, mscorlib");
173 /// var file = type.CreateInstance(@"c:\autoexec.bat");
174 /// if(file.GetPropertyValue&lt;bool&gt;("Exists")) {
175 /// var reader = file.InvokeMethod&lt;StreamReader&gt;("OpenText");
176 /// Console.WriteLine(reader.ReadToEnd());
177 /// reader.Close();
178 /// }
179 /// </code>
180 /// </example>
181 public static object InvokeMethod(this object obj, string methodName, params object[] parameters)
182 {
183 return InvokeMethod<object>(obj, methodName, parameters);
184 }
185
186 /// <summary>
187 /// Dynamically invokes a method using reflection and returns its value in a typed manner
188 /// </summary>
189 /// <typeparam name="T">The expected return data types</typeparam>
190 /// <param name="obj">The object to perform on.</param>
191 /// <param name="methodName">The name of the method.</param>
192 /// <param name="parameters">The parameters passed to the method.</param>
193 /// <returns>The return value</returns>
194 /// <example>
195 /// <code>
196 /// var type = Type.GetType("System.IO.FileInfo, mscorlib");
197 /// var file = type.CreateInstance(@"c:\autoexec.bat");
198 /// if(file.GetPropertyValue&lt;bool&gt;("Exists")) {
199 /// var reader = file.InvokeMethod&lt;StreamReader&gt;("OpenText");
200 /// Console.WriteLine(reader.ReadToEnd());
201 /// reader.Close();
202 /// }
203 /// </code>
204 /// </example>
205 public static T InvokeMethod<T>(this object obj, string methodName, params object[] parameters)
206 {
207 var type = obj.GetType();
208 var method = type.GetMethod(methodName);
209
210 if (method == null)
211 {
212 throw new ArgumentException(string.Format("Method '{0}' not found.", methodName), methodName);
213 }
214
215 var value = method.Invoke(obj, parameters);
216
217 return (value is T ? (T)value : default(T));
218 }
219
220 /// <summary>
221 /// Dynamically retrieves a property value.
222 /// </summary>
223 /// <param name="obj">The object to perform on.</param>
224 /// <param name="propertyName">The Name of the property.</param>
225 /// <returns>The property value.</returns>
226 /// <example>
227 /// <code>
228 /// var type = Type.GetType("System.IO.FileInfo, mscorlib");
229 /// var file = type.CreateInstance(@"c:\autoexec.bat");
230 /// if(file.GetPropertyValue&lt;bool&gt;("Exists")) {
231 /// var reader = file.InvokeMethod&lt;StreamReader&gt;("OpenText");
232 /// Console.WriteLine(reader.ReadToEnd());
233 /// reader.Close();
234 /// }
235 /// </code>
236 /// </example>
237 public static object GetPropertyValue(this object obj, string propertyName)
238 {
239 return GetPropertyValue<object>(obj, propertyName, null);
240 }
241
242 /// <summary>
243 /// Dynamically retrieves a property value.
244 /// </summary>
245 /// <typeparam name="T">The expected return data type</typeparam>
246 /// <param name="obj">The object to perform on.</param>
247 /// <param name="propertyName">The Name of the property.</param>
248 /// <returns>The property value.</returns>
249 /// <example>
250 /// <code>
251 /// var type = Type.GetType("System.IO.FileInfo, mscorlib");
252 /// var file = type.CreateInstance(@"c:\autoexec.bat");
253 /// if(file.GetPropertyValue&lt;bool&gt;("Exists")) {
254 /// var reader = file.InvokeMethod&lt;StreamReader&gt;("OpenText");
255 /// Console.WriteLine(reader.ReadToEnd());
256 /// reader.Close();
257 /// }
258 /// </code>
259 /// </example>
260 public static T GetPropertyValue<T>(this object obj, string propertyName)
261 {
262 return GetPropertyValue<T>(obj, propertyName, default(T));
263 }
264
265 /// <summary>
266 /// Dynamically retrieves a property value.
267 /// </summary>
268 /// <typeparam name="T">The expected return data type</typeparam>
269 /// <param name="obj">The object to perform on.</param>
270 /// <param name="propertyName">The Name of the property.</param>
271 /// <param name="defaultValue">The default value to return.</param>
272 /// <returns>The property value.</returns>
273 /// <example>
274 /// <code>
275 /// var type = Type.GetType("System.IO.FileInfo, mscorlib");
276 /// var file = type.CreateInstance(@"c:\autoexec.bat");
277 /// if(file.GetPropertyValue&lt;bool&gt;("Exists")) {
278 /// var reader = file.InvokeMethod&lt;StreamReader&gt;("OpenText");
279 /// Console.WriteLine(reader.ReadToEnd());
280 /// reader.Close();
281 /// }
282 /// </code>
283 /// </example>
284 public static T GetPropertyValue<T>(this object obj, string propertyName, T defaultValue)
285 {
286 var type = obj.GetType();
287 var property = type.GetProperty(propertyName);
288
289 if (property == null)
290 {
291 throw new ArgumentException(string.Format("Property '{0}' not found.", propertyName), propertyName);
292 }
293
294 var value = property.GetValue(obj, null);
295
296 return (value is T ? (T)value : defaultValue);
297 }
298
299 /// <summary>
300 /// Dynamically sets a property value.
301 /// </summary>
302 /// <param name="obj">The object to perform on.</param>
303 /// <param name="propertyName">The Name of the property.</param>
304 /// <param name="value">The value to be set.</param>
305 public static void SetPropertyValue(this object obj, string propertyName, object value)
306 {
307 var type = obj.GetType();
308 var property = type.GetProperty(propertyName);
309
310 if (property == null)
311 {
312 throw new ArgumentException(string.Format("Property '{0}' not found.", propertyName), propertyName);
313 }
314
315 property.SetValue(obj, value, null);
316 }
317
318 /// <summary>
319 /// Gets the first matching attribute defined on the data type.
320 /// </summary>
321 /// <typeparam name="T">The attribute type tp look for.</typeparam>
322 /// <param name="obj">The object to look on.</param>
323 /// <returns>The found attribute</returns>
324 public static T GetAttribute<T>(this object obj) where T : Attribute
325 {
326 return GetAttribute<T>(obj, true);
327 }
328
329 /// <summary>
330 /// Gets the first matching attribute defined on the data type.
331 /// </summary>
332 /// <typeparam name="T">The attribute type tp look for.</typeparam>
333 /// <param name="obj">The object to look on.</param>
334 /// <param name="includeInherited">if set to <c>true</c> includes inherited attributes.</param>
335 /// <returns>The found attribute</returns>
336 public static T GetAttribute<T>(this object obj, bool includeInherited) where T : Attribute
337 {
338 var type = (obj as Type ?? obj.GetType());
339 var attributes = type.GetCustomAttributes(typeof(T), includeInherited);
340
341 if ((attributes != null) && (attributes.Length > 0))
342 {
343 return (attributes[0] as T);
344 }
345
346 return null;
347 }
348
349 /// <summary>
350 /// Gets all matching attribute defined on the data type.
351 /// </summary>
352 /// <typeparam name="T">The attribute type tp look for.</typeparam>
353 /// <param name="obj">The object to look on.</param>
354 /// <returns>The found attributes</returns>
355 public static IEnumerable<T> GetAttributes<T>(this object obj) where T : Attribute
356 {
357 return GetAttributes<T>(obj);
358 }
359
360 /// <summary>
361 /// Gets all matching attribute defined on the data type.
362 /// </summary>
363 /// <typeparam name="T">The attribute type tp look for.</typeparam>
364 /// <param name="obj">The object to look on.</param>
365 /// <param name="includeInherited">if set to <c>true</c> includes inherited attributes.</param>
366 /// <returns>The found attributes</returns>
367 public static IEnumerable<T> GetAttributes<T>(this object obj, bool includeInherited) where T : Attribute
368 {
369 var type = (obj as Type ?? obj.GetType());
370
371 foreach (var attribute in type.GetCustomAttributes(typeof(T), includeInherited))
372 {
373 if (attribute is T)
374 {
375 yield return (T)attribute;
376 }
377 }
378 }
379
380 #endregion
381 }
382 }