62,242
社区成员




public static class ModelBuilder
{
private static Dictionary<string, PropertyInfo> PropertyDictionary = new Dictionary<string, PropertyInfo>();
public static TModel Build<TModel>(NameValueCollection inputCollection, string namePrefix) where TModel : new()
{
TModel model = new TModel();
Type modelType = model.GetType();
foreach (string elName in inputCollection.AllKeys)
{
if (!elName.StartsWith(namePrefix)) continue;
string value = inputCollection[elName];
if (string.IsNullOrEmpty(value)) continue;
string propName = elName;
if (!string.IsNullOrEmpty(namePrefix))
propName = elName.Substring(namePrefix.Length);
//PropertyInfo prop = modelType.GetProperty(propName); //不使用缓存的
PropertyInfo prop = GetPropertyInfo(modelType, propName); //使用缓存的
if (prop == null) continue;
bool flag = false;
object objValue = null;
Type propType = prop.PropertyType;
try
{
if (propType.IsEnum)
objValue = Enum.Parse(propType, value, true);
else
objValue = Convert.ChangeType(value, propType);
flag = true;
}
catch { }
if (flag)
prop.SetValue(model, objValue, null);
}
return model;
}
private static PropertyInfo GetPropertyInfo(Type modelType, string propertyName)
{
PropertyInfo property = null;
string propertyFullName = string.Format("{0}.{1}", modelType.FullName, propertyName);
if (PropertyDictionary.TryGetValue(propertyFullName, out property))
return property;
property = modelType.GetProperty(propertyName);
if (property != null)
{
lock (PropertyDictionary)
{
PropertyDictionary.Add(propertyFullName, property);
}
}
return property;
}
}
public class TestModel
{
public string Name { get; set; }
public int Count { get; set; }
public bool IsLimit { get; set; }
public DateTime Time { get; set; }
public ModelType Type { get; set; }
}
public enum ModelType
{
Table = 1,
View = 2
}
if (Request.HttpMethod == "POST")
{
DateTime sTime = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
TestModel test = ModelBuilder.Build<TestModel>(Request.Form, "txt");
}
TimeSpan ts = DateTime.Now - sTime;
Response.Write(ts.TotalMilliseconds.ToString());
}
<form method="post">
<input type="text" name="txtName" />
<input type="text" name="txtCount" />
<input type="text" name="txtIsLimit" />
<input type="text" name="txtTime" />
<input type="text" name="txtType" />
<input type=submit input="提交" />
</form>