Asp.net下的对象成员数据绑定器实现 (3)
通过ConverterAttribute可以方便制定粒度更小的配置
private byte[] mFileStream;
[Converter(typeof(FileStreamConverter),"IconPhoto")]
public byte[] FileStream
{
get
{
return mFileStream;
}
set
{
mFileStream = value;
}
}
以上定义可以上传文件流转成byte[]到FileStream属性中。
功能集成实现
现在就把所有东西集成起来,满足目的的要求。
public object Bind(System.Collections.Specialized.NameValueCollection values, string prefix)
{
object newobj = Activator.CreateInstance(ObjectType);
if (prefix == null)
prefix = "";
object value;
foreach (PropertyInfo item in Properties)
{
value = values[prefix + "." + item.Name];
if(value == null)
value = values[prefix + "_" + item.Name];
if(value == null)
value = values[prefix + item.Name];
BindProperty(newobj, item, (string)value);
}
return newobj;
}
private void BindProperty(object obj, PropertyInfo property, string value)
{
IStringConverter stringconver;
object nvalue;
bool confirm = false;
Object[] cas = property.GetCustomAttributes(typeof(ConverterAttribute), true);
if (cas.Length > 0)
{
nvalue = ((ConverterAttribute)cas[0]).ConvertTo(value, out confirm);
if (confirm)
mPropertiesHandle[property].SetValue(obj, nvalue);
}
else
{
if (ConverterFactory.Converters.ContainsKey(property.PropertyType))
{
stringconver = ConverterFactory.Converters[property.PropertyType];
nvalue = stringconver.ConvertTo(value, out confirm);
if (confirm)
mPropertiesHandle[property].SetValue(obj, nvalue);
}
}
}
因为Web提交的数据几乎可以通过HttpRequest.Params得到,只需要根据属性名称和相关前缀进行匹配查找就可以了。这里实现的匹配方式并不理想,其实可以在相关page第一次请求就可以分析到关系存在IDictionary中,后期直接使用就可以了。
以上功能是在编写一个MVC组件的数据绑定功能,其实完全可以移植传统的WebForm下工作;有更好想法的朋友请多提交意见。

[
1] [
2]
[3] 