ol.GetType());
foreach (var property in metadata.Keys)
{
object value = GetValue(metadata[property], context) ?? GetDefaultValue(property);
if (value != null)
{
property.SetValue(control, Convert.ChangeType(value, property.PropertyType), null);
}
}
}
SetPropertyValues方法中会调用三个方法:GetMetadata,GetValue和GetDefaultValue。GetMetadata方法会得到关于这个control的元数据,为PropertyInfo - List<UserControlRenderingPropertyAttribute>的键值对(即Dictionary)。然后将metadata传入GetValue方法,以获取由UserControlRenderingPropertyAttribute标记的值。如果GetValue方法返回null,则调用GetDefaultValue方法获取标记在该属性上DefaultValueAttribute。以下就将其余代码附上,没有技术含量,但做一参考:
[展开代码]
private static Dictionary<
Type,
Dictionary<
PropertyInfo,
List<UserControlRenderingPropertyAttribute>>> s_metadataCache =
new Dictionary<
Type,
Dictionary<
PropertyInfo,
List<UserControlRenderingPropertyAttribute>>>();
private static Dictionary<PropertyInfo, object> s_defaultValueCache =
new Dictionary<PropertyInfo,object>();
private static object s_mutex = new object();
private static Dictionary<
PropertyInfo,
List<UserControlRenderingPropertyAttribute>> GetMetadata(Type type)
{
if (!s_metadataCache.ContainsKey(type))
{
lock (s_mutex)
{
if (!s_metadataCache.ContainsKey(type))
{
s_metadataCache[type] = LoadMetadata(type);
}
}
}
return s_metadataCache[type];
}
private static Dictionary<
PropertyInfo,
List<UserControlRenderingPropertyAttribute>> LoadMetadata(Type type)
{
var result = new Dictionary<PropertyInfo, List<UserControlRenderingPropertyAttribute>>();
PropertyInfo properties = type.GetProperties(
BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
foreach (var p in properties)
{
var attributes = p.GetCustomAttributes(
typeof(UserControlRenderingPropertyAttribute), true);
if (attributes.Length > 0)
{
result[p] = new List<UserControlRenderingPropertyAttribute>(
attributes.Cast<UserControlRenderingPropertyAttribute>());
}
}
return result;
}
private static object GetDefaultValue(PropertyInfo property)
{
if (!s_defaultValueCache.ContainsKey(property))
{
lock (s_mutex)
{
if (!s_defaultValueCache.ContainsKey(property))
{
var attributes = property.GetCustomAttributes(typeof(DefaultValueAttribute), true);
object value = attributes.Length > 0 ?
((DefaultValueAttribute)attributes[0]).Value : null;
s_defaultValueCache[property] = value;
}
}
}
return s_defaultValueCache[property];
}
private static void SetPropertyValues(UserControl control, HttpContext context)
{
var metadata = GetMetadata(control.GetType());
foreach (var property in metadata.Keys)
{
object value = GetValue(metadata[property], context) ?? GetDefaultValue(property);
if (value != null)
{
property.SetValue(control, Convert.ChangeType(value, property.PropertyType), null);
}
}
}
private static object GetValue(
IEnumerable<UserControlRenderingPropertyAttribute> metadata,