Creating a generic IList instance using reflection
Tag : chash , By : ffmmjj
Date : March 29 2020, 07:55 AM
This might help you I am trying to create a generic list of objects using reflection. The below code throws an error Cannot create an instance of an interface. . I could change the IList to List and it works fine, but I was wondering if there is way to get this working with an IList. , you'll have to instatiate a concrete class so if you do var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName);
var list = (Ilist<T>)Activator.CreateInstance(type);
|
Get generic instance generic type using reflection
Tag : chash , By : user121350
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Given: typeof(List<string>).GetGenericTypeDefinition() == typeof(List<>)
|
Reflection: Type of item contained in non-generic subclass of generic list
Tag : chash , By : Hans-Inge
Date : March 29 2020, 07:55 AM
I wish this helpful for you var elementType = (
from iface in myList.GetType().GetInterfaces()
where iface.IsGenericType
where iface.GetGenericTypeDefinition() == typeof(IList<>)
select iface.GetGenericArguments()[0])
.Single();
|
Add instance of Generic List to object using reflection
Tag : chash , By : pdkent
Date : March 29 2020, 07:55 AM
will help you Im running the code from your question with some minor changes to make it compile and it seems to work fine: void Main()
{
Parse<Foo>();
}
public static T Parse<T>() where T : new()
{
var returnObj = new T();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo p in properties)
{
// Get a meaningful property name
string ins = p.PropertyType.Name;
switch(ins)
{
// populate int
case "Int32":
p.SetValue(returnObj, 1 , null);
break;
// populate list
case "IList`1":
var list = new List<string>();
// This will throw the exception 'Parameter count mismatch.'
p.SetValue(returnObj, list, null);
break;
}
}
return returnObj;
}
public class Foo
{
public virtual int someInt {get; set;}
public virtual IList<string> list {get; set;}
}
public class Foo
{
public virtual int someInt {get; set;}
public virtual IList<string> this[int key]
{
get{ return null; }
set
{
}
}
}
|
How to add an object to a generic list property of an instance of a class using reflection
Tag : chash , By : NeedOptic
Date : March 29 2020, 07:55 AM
it fixes the issue I have a class structure below. I am getting this error. Am i missing something here? , It should be something like this: // gets metadata of List<Lecture>.Add method
var addMethod = pi.PropertyType.GetMethod("Add");
// retrieves current LectureList value to call Add method
var lectureList = pi.GetValue(s);
// calls s.LectureList.Add(obj);
addMethod.Invoke(lectureList, new object[] { obj });
|