How to create a List<unknown type at compile time> and copy items via System.Reflection.PropertyInfo
I have come across something pretty complex. I would be obliged if anyone can help.
1) I have to create a List<> of unknown type at compile time. That I have already achieved.
Type customList = typeof(List<>).MakeGenericType(tempType);
object objectList = (List<object>)Activator.CreateInstance(customList);
"temptype" is the custom type thats been already fetched.
2) Now I have PropertyInfo
object which is that list from which I have to copy all items to t开发者_C百科he the instance that I have just created "objectList"
3) Then I need to iterate and access the items of "objectList" as if it were a "System.Generic.List".
Cutting long story short, using reflection I need to extract a property that is a list and have it as an instance for further use. Your suggestions would be appreciated. Thanks in Advance.
Umair
Many of the .NET generic collection classes also implement their non-generic interfaces. I'd make use of these to write your code.
// Create a List<> of unknown type at compile time.
Type customList = typeof(List<>).MakeGenericType(tempType);
IList objectList = (IList)Activator.CreateInstance(customList);
// Copy items from a PropertyInfo list to the object just created
object o = objectThatContainsListToCopyFrom;
PropertyInfo p = o.GetType().GetProperty("PropertyName");
IEnumerable copyFrom = p.GetValue(o, null);
foreach(object item in copyFrom) objectList.Add(item); // Will throw exceptions if the types don't match.
// Iterate and access the items of "objectList"
// (objectList declared above as non-generic IEnumerable)
foreach(object item in objectList) { Debug.WriteLine(item.ToString()); }
Do you think this would help you? Efficient way of updating a collection from another collection
I came up with something similar. I borrowed the SetProperties()
method from NullSkull and wrote a simple method that calls the NullSkull SetProperties()
:
public static List<U> CopyList<T, U>(List<T> fromList, List<U> toList)
{
PropertyInfo[] fromFields = typeof(T).GetProperties();
PropertyInfo[] toFields = typeof(U).GetProperties();
fromList.ForEach(fromobj =>
{
var obj = Activator.CreateInstance(typeof(U));
Util.SetProperties(fromFields, toFields, fromobj, obj);
toList.Add((U)obj);
});
return toList;
}
...so with one line of code I can retrieve a List<desired class>
populated with matching values by name from List<source class>
as follows:
List<desired class> des = CopyList(source_list, new List<desired class>());
As far as performance goes, I didn't test it, as my requirements call for small lists.
精彩评论