Recognize TypeConverterAttributes on properties to override default getter semantics.
[castle.git] / Components / DictionaryAdapter / Castle.Components.DictionaryAdapter / DefaultPropertyGetter.cs
blob634e1ee0582e854a3105b3ee3281eae66b79b915
1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.Components.DictionaryAdapter
17 using System;
18 using System.Collections;
19 using System.ComponentModel;
21 /// <summary>
22 /// Manages conversion between property values.
23 /// </summary>
24 public class DefaultPropertyGetter : IDictionaryPropertyGetter
26 private readonly TypeConverter converter;
28 /// <summary>
29 /// Singleton instance of <see cref="DefaultPropertyGetter"/>
30 /// </summary>
31 public static readonly DefaultPropertyGetter
32 Instance = new DefaultPropertyGetter();
34 /// <summary>
35 /// Initializes a new instance of the <see cref="DefaultPropertyGetter"/> class.
36 /// </summary>
37 public DefaultPropertyGetter()
41 /// <summary>
42 /// Initializes a new instance of the <see cref="DefaultPropertyGetter"/> class.
43 /// </summary>
44 /// <param name="converter">The converter.</param>
45 public DefaultPropertyGetter(TypeConverter converter)
47 this.converter = converter;
50 /// <summary>
51 /// Gets the effective dictionary value.
52 /// </summary>
53 /// <param name="factory">The dictionary factory.</param>
54 /// <param name="dictionary">The dictionary.</param>
55 /// <param name="key">The key.</param>
56 /// <param name="storedValue">The stored value.</param>
57 /// <param name="property">The property.</param>
58 /// <returns>The effective property value.</returns>
59 public object GetPropertyValue(IDictionaryAdapterFactory factory,
60 IDictionary dictionary, string key,
61 object storedValue, PropertyDescriptor property)
63 Type propertyType = property.PropertyType;
65 if (storedValue != null && !propertyType.IsInstanceOfType(storedValue))
67 TypeConverter conv = converter ?? TypeDescriptor.GetConverter(propertyType);
68 if (conv != null && conv.CanConvertFrom(storedValue.GetType()))
70 return conv.ConvertFrom(storedValue);
74 return storedValue;