Enumeration in the general list of variables of dynamic type

I need to change the property of a Capacitydynamic type variable List<*DynamicType*>. The problem is that it Activatorreturns the object-casted variable if the type of the variable is not specified instead of the correct one List<*DynamicType*>, and the best I can do is pass it to IList:

DynamicTypeBuilder builder = new DynamicTypeBuilder() { ... };
Type dataType = builder.GenerateType(...);
Type listDataType = typeof(List<>).MakeGenericType(dataType);
IList list = (IList)Activator.CreateInstance(listDataType);

After some searches, I found only one hack:

dynamic dynamicList = list;
dynamicList.Capacity = dataRowsCount;

Although that would be acceptable in my case, I wonder if there is another way to do this.

+5
source share
2 answers

Perhaps this is easier:

object list = Activator.CreateInstance(listDataType,
    new object[]{dataRowsCount});

Which should use the correct constructor?

. dynamic hack , ( , ), dynamic ( ), . , , dynamic , :

void Evil<T>(List<T> list, int capacity) {
    list.Capacity = capacity;
    // do other stuff
}
...
dynamic list = Activator.CreateInstance(listDataType);
Evil(list, dataRowsCount);

T. , .

+3

:

var capacityProperty = listDataType.GetProperty("Capacity");
capacityProperty.SetValue(list, dataRowsCount, null);

, , , , . , .

+4

All Articles