vendredi 25 août 2017

Clear/add to a properties/fields on an object whose type is ICollection

Let's say I have a simple class like so:

public class SimpleClass
{
    public List<SomeOtherClass> ListOfStuff { get; } = new List<SomeOtherClass>();
}

SimpleClass itself is unimportant, let's say I've interrogated the type and determined it's of interest for some reason, so all I have is the System.Type object. Now say that I want to access any non static properties/fields on the class that implement ICollection<T> (i.e. ListOfStuff on SimpleClass). I can access/create instances of SimpleClass and I can also dynamically create instances of whatever the collection is made of, but how do I dynamically (and as efficiently as possible) clear or add items to ListOfStuff.

Basically I want to be able to create delegates that I can call later that I can pass an instance of the interested type to, and the method will clear a specific property/field on a class, and then similarly I want another which I can also pass a instance of the collection's item to (e.g. SomeOtherClass), and it will add it to the collection on the property.

I have the System.Type of the class I'm interested in, I have the PropertyInfo/FieldInfo of the field(s) I'm interested in, and I can create instances of the class and the item used in the collection.

e.g. (this is not real code!)

Type type = typeof(SimpleClass);
...
// CreateNew is a method that somehow returns a new instance of a type
object test = CreateNew(type);

// GetCollections somehow returns properties/fields that implement ICollection<>
foreach(var collection in GetCollections(type))
{
    // CreateNewCollection somehow returns a new instance of the item used in the collection
    object newItem = CreateNewCollectionItem(collection);

    // how do I implement these two lines?
    var clear = Delegate.CreateDelegate(...);
    var add = Delegate.CreateDelegate(...);
    ...
    clear(test);
    add(test, newItem);
}

How can I make these delegates?





Aucun commentaire:

Enregistrer un commentaire