如何在运行时添加到对象的未知列表属性



我有一个'Profile'对象/类与'地址'列表,其中,我将只知道他们的类型[Profile/地址]在运行时通过GetType()/GetProperties()等,虽然我希望。添加到这个列表,例如:

var profile = session.Get<ProfileRecord>(1);
dynamic obj = new ExpandoObject();
obj = profile;
obj["Addresses"].Add(addressNew);

由于:

不能用[]对type的表达式应用索引"Test.Models.ProfileRecord"。

我一直在看字典,但是我的尝试都没有成功,甚至不知道我是否应该沿着这条路走下去——那么正确的方法是什么呢?这整个概念对我来说都是新的,所以请不要过度假设我的能力。

如果您不知道配置文件的类型,您可以这样做。

var prop = profile.GetType().GetProperty("Addresses").GetValue(profile);
prop.GetType().GetMethod("Add").Invoke(prop, new object[] {1}); // Add the Value to the list

但是你必须确保List已经被初始化了。

但我认为你应该能够转换你的对象,并设置属性直接像:

if(profile.GetType == typeof (ProfileRecord))
{
    var record = (ProfileRecord)profile;
    if (profile.Addresses == null)
    {
         profile.Addresses = new List<Address>();
    }
    prfile.Addresses.Add(addressNew);
}

最新更新