简体   繁体   中英

C# How to set PropertyInfo value when its type is a List<T> and I have a List<object>

I have an object with a generic List property where T is a primitive value, string, or enum. The generic argument of this list will never be a reference type (except for string). Now, I have another List who's argument type is object. Is there a way to set that property's value with my object list? As in:

List<object> myObjectList = new List<object>();
myObjectList.Add(5);

property.SetValue(myObject, myObjectList, null);

When I know that the property's real type is:

List<int>

The only solution I can see to it is making a hard coded switch that uses the generic argument's type of the list property and creates a type safe list. But it would be best if there were a general case solution. Thanks!

You should create an instance of the property's real type, if you know it really will be a List<T> for some T (rather than an interface, for example). You can then cast to IList and add the values to that, without knowing the actual type.

object instance = Activator.CreateInstance(property.PropertyType);
// List<T> implements the non-generic IList interface
IList list = (IList) instance;
list.Add(...); // Whatever you need to add

property.SetValue(myObject, list, null);

Yes there is - you can do something like this:

property.SetValue(myObject, myObjectList.Cast<int>().ToList(), null);

this is using Enumerable.Cast so note that this will throw an runtime exception if there are values not of type int in your list.

It's a little embarrassing to write something here besides the giants above, but I've struggled a lot with the subject, so others should not:

public class Father
{
    public string id { get; set; }
    public List<string> child { get; set; }
}
Father = new();
Father.child = new();
List<string> valSource = new();
valSource.Add(..);//may in a loop
Faher.child = (System.Collections.Generic.List<string>)valSource;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM