In my application, I have a Reflection.PropertyInfo
variable named 'property'. When I do a property.GetValue(myObject,null)
, the value is Master.Enterprise
. Enterprise is a class in my application. So, 'property' contains a reference to a class in my app.
At runtime, I would like to somehow cast 'property' to its type (Master.Enterprise
) so I can use it as if it were the class type.
I know this can be done because when I look at the code in the debugger, the debugger correctly casts 'property' to the type its referencing, and I can see all the properties of the Enterprise class in the debugger.
How might I go about doing this?
It sounds to me like you need to define an interface - you can then require that your property returns an object that implements that interface, and you will then be able to cast into that interface regardless of what class implements that interface:
IEnterprise enterprise = (IEnterprise)property.GetValue(myObject, null);
The only other option you have is to call methods and properties on the returned object using reflection - this is what the visual studio debugger is doing.
Master.Enterprise enterprise = (Master.Enterprise)property.GetValue(myObject,null);
or
Master.Enterprise enterprise = property.GetValue(myObject,null) as Master.Enterprise;
The first will throw an exception if the type is not compatible. The second will return null if not compatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With