【发布时间】:2013-06-16 22:40:39
【问题描述】:
我正在尝试编写一个函数来创建类型 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?
【问题讨论】:
-
你为什么要使用
dynamic?如果你用反射做所有事情,我看不出你实际上在做任何利用它的事情dynamic。 -
对不起,我对
Reflection命名空间了解不多。
标签: c# c#-4.0 dynamic reflection types