Question

I have a IRecord object that can hold objects. The name of these objects is saved in mapping as Properties. I loop through the properties and get them out of the IRecord by doing

record[property]

These objects are always ICollections. However, I don't know what type the ICollection will hold before hand. How can I unbox the object to the right ICollection without knowing what the ICollection will hold?

The code below is a working version if record[property is an IColletion, so I want to change this that it can take any ICollection.

public ElectronicSignatureModel SignHierarchy(IRecord record, List<HierarchyMapping> mapping)
    {
        foreach (HierarchyMapping hierarchyMapping in mapping)
        {

            string[] propertyList = hierarchyMapping.Properties;
            foreach (string property in propertyList)
            {
                ICollection<Sample> recordProperty = (ICollection<Sample>)record[property];
            }
        }
Was it helpful?

Solution

You can use .NET reflection to dynamically get value of a property in a object in the runtime. even you can use it to invoke a method or or create class instance.

You can try something like the following code:

foreach (string property in propertyList)
{
    PropertyInfo pinfo = record.GetType().GetProperty(property);
    var recordProperty = pinfo.GetValue(record, null);
}

the "recordProperty" should have the right ICollection now, then you can use it.

You can read more about .NET reflection here:

Reflection in .NET http://www.codeproject.com/Articles/55710/Reflection-in-NET

Reflection in the .NET Framework http://msdn.microsoft.com/en-us/library/f7ykdhsy(v=vs.100).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top