我想寫一個函數,它創建一個類型爲t的對象並分配它的屬性。如何將C#動態變量屬性分配給另一個動態對象?
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'?如果你用反射來做所有的事情,我看不到你實際上在做任何使用「動態」的東西。 –
對不起,我對「Reflection」命名空間不太瞭解。 –