public class USER
{
public string id { get; set; }
public string username { get; set; }
}
static readonly Type modelType = typeof(USER);
void main{
Dictionary<String, Object> dic= new Dictionary<String, Object>();
dic.Add(1,"小明");
dic.Add(2,"小京");
var model = ReturnObject<USER>(dic, modelType );
.......执行补充输出测试
}
internal static T ReturnObject<T>(Dictionary<string, object> models, Type modelsType)
{
Object myObject = Activator.CreateInstance<T>();
foreach (var pi in modelsType.GetProperties())
{
object outObj = new object();
if (models.TryGetValue(pi.Name.ToLower(), out outObj))
{
var outType = outObj.GetType();
if (outType == pi.PropertyType)
pi.SetValue(myObject, outObj, null);
}
}
return (T)myObject;
}
//重点提示:大家错的最多的就是传入时候是class,还是struct,注意进入方法ReturnObject对应的泛型对象。