|
Using System;
Using System.Collections.Specialized;
Using System.Reflection;
Using System.Web;
Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
Person person = createinstance<person> ("name=dnawo&age=20&birthday=2014-07-23");
Console.WriteLine ("{0},{1},{2}", person.) Name, person. Age, person. Birthday);
Console.readkey ();
}
///<summary>
///Create generic instance
///</summary>
///<typeparam name= "T" ></typeparam>
///<param name= "Data" ></PARAM>
///<returns></returns>
Static T CreateInstance <T> (string data) where T:class
{
T result = activator.createinstance<t> ();
NameValueCollection NV = httputility.parsequerystring (data);
Propertyinfo[] Properties = typeof (T). GetProperties ();
foreach (PropertyInfo prop in properties)
{
String name = Prop. Propertytype.name;
String value = Nv[prop. Name];
if (value!= null)
{
if (name = = typeof (String). Name)
{
Prop. SetValue (result, value, NULL);
}
Else if (name = = typeof (int). Name)
{
Prop. SetValue (result, int. Parse (value), NULL);
}
Else if (name = = typeof (DateTime). Name)
{
Prop. SetValue (result, datetime.parse (value), NULL);
}
}
return result;
}
}
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
Public DateTime Birthday {get; set;}
}
}
|