62,269
社区成员
发帖
与我相关
我的任务
分享public static class ModelBuilder
{
public static TModel Build<TModel>(NameValueCollection itemCollection) where TModel : new()
{
Type type = typeof(TModel);
TModel model = new TModel();
foreach (string name in itemCollection.AllKeys)
{
PropertyInfo property = type.GetProperty(name);
if (property != null)
{
object input;
Type t = property.PropertyType;
bool flag = TryParseValue(itemCollection[name], t, out input);
if (flag)
property.SetValue(model, input, null);
}
}
return model;
}
//1.感觉此部分不够优雅,还请大虾给出更好的实现方法
//2.仅实现了部分.NET基础类型的转换
private static bool TryParseValue(string input, Type type, out object result)
{
result = string.Empty;
if (string.IsNullOrEmpty(input)) return false;
bool flag = false;
string typeName = type.FullName;
switch (typeName)
{
case "System.String" :
result = input;
return true;
case "System.Int16" :
Int16 r1;
flag = Int16.TryParse(input, out r1);
result = r1;
return flag;
case "System.Int32" :
int r2;
flag = int.TryParse(input, out r2);
result = r2;
return flag;
case "System.Int64" :
Int64 r3;
flag = Int64.TryParse(input, out r3);
result = r3;
return flag;
case "System.DateTime" :
DateTime r4;
flag = DateTime.TryParse(input, out r4);
result = r4;
return flag;
case "System.Boolean" :
if (input == "1" || string.Compare(input, "true", true) == 0)
result = true;
else
result = false;
return true;
default :
return false;
}
}
}public class TestModel
{
public string Name { get; set; }
public int Count { get; set; }
public bool IsLimit { get; set; }
public DateTime Time { get; set; }
}if (Request.HttpMethod == "POST")
{
TestModel test = ModelBuilder.Build<TestModel>(Request.Form);
Response.Write("Done");
}<form method="post">
<input type="text" name="Name" />
<input type="text" name="Count" />
<input type="text" name="IsLimit" />
<input type="text" name="Time" />
<input type=submit input="提交" />
</form>
public static class ModelBuilder
{
private static Dictionary<string, PropertyInfo> PropertyDictionary = new Dictionary<string, PropertyInfo>();
public static TModel Build<TModel>(NameValueCollection itemCollection, string namePrefix) where TModel : new()
{
TModel model = new TModel();
Type modelType = typeof(TModel);
foreach (string name in itemCollection.AllKeys)
{
if (!name.StartsWith(namePrefix)) continue;
string value = itemCollection[name];
if (string.IsNullOrEmpty(value)) continue;
string propName = name;
if (!string.IsNullOrEmpty(namePrefix))
propName = name.Substring(namePrefix.Length);
PropertyInfo prop = GetPropertyInfo(modelType, propName); //modelType.GetProperty(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;
}
}
TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(properties.Get(str))
Convert.ChangeType(value, propertyType);
//这俩都是类型转换,有啥区别没?或者用哪个性能更好?
//我偷偷测试去
public void SetProerties(NameValueCollection properties)
{
foreach (string str in properties)
{
PropertyInfo property = base.GetType().GetProperty(str);
if (property != null)
{
property.SetValue(this, TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(properties.Get(str)), null);
}
}
}public static class ModelBuilder
{
public static TModel Build<TModel>(NameValueCollection itemCollection, string namePrefix) where TModel : new()
{
TModel model = new TModel();
Type modelType = typeof(TModel);
foreach (string name in itemCollection.AllKeys)
{
string value = itemCollection[name];
if (string.IsNullOrEmpty(value)) continue;
string propertyName = name;
if (!string.IsNullOrEmpty(namePrefix))
propertyName = name.Substring(namePrefix.Length);
PropertyInfo property = modelType.GetProperty(propertyName);
if (property == null) continue;
bool flag = false;
object objValue = null;
Type propertyType = property.PropertyType;
try
{
if (propertyType.IsEnum)
objValue = Enum.Parse(propertyType, value, true);
else
objValue = Convert.ChangeType(value, propertyType);
flag = true;
}
catch { }
if (flag)
property.SetValue(model, objValue, null);
}
return model;
}
} 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");
//第二种方式
TestModel test = new TestModel();
try
{
test.Name = Request.Form["txtname"];
test.Count = int.Parse(Request.Form["txtcount"]);
test.IsLimit = string.Compare("true", Request.Form["txtIsLimit"], true) == 0;
test.Time = DateTime.Parse(Request.Form["txtTime"]);
}
catch { }
}
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>public static class ModelBuilder
{
public static TModel Build<TModel>(NameValueCollection itemCollection) where TModel : new()
{
Type type = typeof(TModel);
TModel model = new TModel();
foreach (string name in itemCollection.AllKeys)
{
string value = itemCollection[name];
if (string.IsNullOrEmpty(value)) continue;
PropertyInfo property = type.GetProperty(name);
if (property != null)
{
Type t = property.PropertyType;
object objValue = null;
if (t.IsEnum)
objValue = Enum.Parse(t, value, true);
else
objValue = Convert.ChangeType(itemCollection[name], t);
property.SetValue(model, objValue, null);
}
}
return model;
}
}
Convert.ChangeType(object, type)
//一个对象,它的 Type 为 conversionType,而且它的值等效于 value。 - 或 - 如果 value 为空引用(在 Visual Basic 中为 Nothing) 且 //conversionType 不是值类型,则为空引用(在 Visual Basic 中为 Nothing)。
switch (property[i].PropertyType.Name.Trim().ToLower())
{
case "datetime":
DateTime dateTimeValue;
if (value == null || value.ToString().Trim().Length == 0)
{
dateTimeValue = Convert.ToDateTime("1900-01-01");
}
else
{
dateTimeValue = Convert.ToDateTime(value);
}
property[i].SetValue(objReturn, dateTimeValue, null);
break;
case "int32":
Int32 intValue;
if (value == null || value.ToString().Trim().Length == 0)
{
intValue = 0;
}
else
{
intValue = Convert.ToInt32(value);
}
property[i].SetValue(objReturn, intValue, null);
break;
case "int64":
Int64 intValue64;
if (value == null || value.ToString().Trim().Length == 0)
{
intValue64 = 0;
}
else
{
intValue64 = Convert.ToInt32(value);
}
property[i].SetValue(objReturn, intValue64, null);
break;
case "decimal":
decimal decValue;
if (value == null || value.ToString().Trim().Length == 0)
{
decValue = 0;
}
else
{
decValue = Convert.ToDecimal(value);
}
property[i].SetValue(objReturn, decValue, null);
break;
case "double":
double doubleValue;
if (value == null || value.ToString().Trim().Length == 0)
{
doubleValue = 0;
}
else
{
doubleValue = Convert.ToDouble(value);
}
property[i].SetValue(objReturn, doubleValue, null);
break;
case "boolean":
bool boolValue;
if (value == null || value.ToString().Trim().Length == 0)
{
boolValue = false;
}
else
{
boolValue = Convert.ToBoolean(value);
}
property[i].SetValue(objReturn, boolValue, null);
break;
default:
//string
property[i].SetValue(objReturn, value, null);
break;
}