我正在尝试编写一个函数来创建类型 t 的对象并分配其属性。
internal static object CreateInstanceWithParam(Type t, dynamic d)
{
//dynamic obj = t.GetConstructor(new Type[] { d }).Invoke(new object[] { d });
dynamic obj = t.GetConstructor(new Type[] { }).Invoke(new object[] { });
foreach (var prop in d.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
//prop.Name,
//prop.GetValue(d, null);
// assign the properties and corresponding values to newly created object ???
}
return obj;
}
然后我应该可以将它用于任何类型的类类型,例如
IUser user = (IUser)CreateInstanceWithParam(userType, new { UserID = 0, Name = "user abc", LoginCode = "abc", DefaultPassword = "xxxxxx" });
IUnit newUnit = (IUnit)CreateInstanceWithParam(unitType, new { ID = 3, Code = "In", Name = "Inch", Points = "72" })
如何将属性分配prop.Name
给obj
?