如何在运行时添加到对象的未知列表 属性?
How to Add to an unknown List property of an object at runtime?
我有一个 'Profile' object/class,其 IList 为 'Addresses',其中,我只会在运行时通过 GetType() / GetProperties 知道它们的类型 [profile / addresses] () 等,尽管我希望添加到此列表中,例如:
var profile = session.Get<ProfileRecord>(1);
dynamic obj = new ExpandoObject();
obj = profile;
obj["Addresses"].Add(addressNew);
由于以下原因,这不起作用:
Cannot apply indexing with [] to an expression of type
'Test.Models.ProfileRecord'.
我一直在查看 IDictionary,但我的尝试一直没有成功,甚至不知道我是否应该沿着那条路走下去 - 那么正确的方法是什么?整个概念对我来说都是新的,所以请不要过度假设我的能力 ;) 非常感谢。
如果您不知道配置文件的类型,可以这样做。
var prop = profile.GetType().GetProperty("Addresses").GetValue(profile);
prop.GetType().GetMethod("Add").Invoke(prop, new object[] {1}); // Add the Value to the list
但是你必须确保列表已经初始化。
但我认为您应该能够投射对象并直接设置 属性,例如:
if(profile.GetType == typeof (ProfileRecord))
{
var record = (ProfileRecord)profile;
if (profile.Addresses == null)
{
profile.Addresses = new List<Address>();
}
prfile.Addresses.Add(addressNew);
}
我有一个 'Profile' object/class,其 IList 为 'Addresses',其中,我只会在运行时通过 GetType() / GetProperties 知道它们的类型 [profile / addresses] () 等,尽管我希望添加到此列表中,例如:
var profile = session.Get<ProfileRecord>(1);
dynamic obj = new ExpandoObject();
obj = profile;
obj["Addresses"].Add(addressNew);
由于以下原因,这不起作用:
Cannot apply indexing with [] to an expression of type 'Test.Models.ProfileRecord'.
我一直在查看 IDictionary,但我的尝试一直没有成功,甚至不知道我是否应该沿着那条路走下去 - 那么正确的方法是什么?整个概念对我来说都是新的,所以请不要过度假设我的能力 ;) 非常感谢。
如果您不知道配置文件的类型,可以这样做。
var prop = profile.GetType().GetProperty("Addresses").GetValue(profile);
prop.GetType().GetMethod("Add").Invoke(prop, new object[] {1}); // Add the Value to the list
但是你必须确保列表已经初始化。
但我认为您应该能够投射对象并直接设置 属性,例如:
if(profile.GetType == typeof (ProfileRecord))
{
var record = (ProfileRecord)profile;
if (profile.Addresses == null)
{
profile.Addresses = new List<Address>();
}
prfile.Addresses.Add(addressNew);
}