jeudi 11 août 2016

.NET reflection cast to exact type

i wonder if there is a way to cast to exact type using system.reflection so that you will avoid doing explicit cast such as

(System.DateTime)

for example

Assuming i would have a Dictionary such as

Dictionary<propName, Dictionary<object, Type>>

and assuming i iterate over an object props list

foreach (var prop in @object.GetType().GetProperties())
{
       object propValue = propInfo.GetValue(@object, null);
       string propName = propInfo.Name;

       Dictionary<object, Type> typeDictionary = new Dictionary<object, Type>();
       Type propType = propInfo.GetValue(@object, null).GetType();
       typeDictionary[propValue ] = propType ;

       propsDictionary[propInfo.Name] = propValue;
}

I would like to do something like , cast to exact type using something like

// this part is only for guidelines 
// it should obtain the exact Type 
// ... but it returns a string of that type Namespace.Type
Type exactType = Dictionary[enumOfPropName][someValue] 
// this part should know the exact type Int32 for example and cast to exact 
var propX = (exactType)someValue

Is there any way of doing such thing and if so how can i obtain this? Also most of this code is just a guideline, an idea so please don't take it likely. Thank you all.





Aucun commentaire:

Enregistrer un commentaire