不囉唆,直接看 code
public static FormCollection FillTo(this FormCollection form, object target, Func<FormCollection, string, object> getValue)
{
Type targetType = target.GetType();
foreach (var property in targetType.GetProperties())
{
//檢查 form 中有沒有值
if (Array.IndexOf(form.AllKeys, property.Name) != -1)
{
object value = getValue(form, property.Name);
if ((property.PropertyType == typeof(System.Guid)) || (property.PropertyType == typeof(System.Guid?)))
value = new Guid(value as string);
else if ((property.PropertyType == typeof(System.DateTime)) || (property.PropertyType == typeof(System.DateTime?)))
value = Convert.ToDateTime(value);
else if ((property.PropertyType == typeof(System.Int16)) || (property.PropertyType == typeof(System.Int16?)))
value = Convert.ToInt16(value);
else if ((property.PropertyType == typeof(System.Int32)) || (property.PropertyType == typeof(System.Int32?)))
value = Convert.ToInt32(value);
else if ((property.PropertyType == typeof(System.Int64)) || (property.PropertyType == typeof(System.Int64?)))
value = Convert.ToInt64(value);
else if ((property.PropertyType == typeof(System.Byte)) || (property.PropertyType == typeof(System.Byte?)))
value = Convert.ToByte(value);
else if ((property.PropertyType == typeof(System.Boolean)) || (property.PropertyType == typeof(System.Boolean?)))
value = BoolParseEX(value as string);
else if ((property.PropertyType == typeof(System.Char)) || (property.PropertyType == typeof(System.Char?)))
value = Convert.ToChar(value);
else if ((property.PropertyType == typeof(System.Decimal)) || (property.PropertyType == typeof(System.Decimal?)))
value = Convert.ToDecimal(value);
else if ((property.PropertyType == typeof(System.Double)) || (property.PropertyType == typeof(System.Double?)))
value = Convert.ToDouble(value);
else if ((property.PropertyType == typeof(string))) // || (property.PropertyType == typeof(string?)))
value = Convert.ToString(value);
else
throw new Exception(string.Format("value type not support!! {0}", property.PropertyType.FullName));
try
{
property.SetValue(target, value, null);
}
catch
{
//ignore
}
}
}
return form;
}
因為 c# 2.0 加入了 Nullable