简体   繁体   中英

C# cast Type to generic strong typed

I'm enumerating my EntityFramework Container properties. Through reflection I get only DbSet properties. Now I need to access the property value and I tried it this way:

object obj = PropertyInfo.GetValue(myobject) 

All right here but I need to cast to its real type (I ideally need this):

DbSet<MyRealType> obj = ( DbSet<MyRealType> )PropertyInfo.GetValue(myobject);

But MyRealType is unknown at compile time. I only get a Type but i can cast it to DbSet<MyrealType> . Is it possible to achieve that?

No, this is going to be impossible. What you're attempting to do is convert a run time type into a compile time type, and many a programmer has attempted and failed to do so. Your options at this point will mostly involve inspecting the type with reflection and attempting to invoke methods and properties off that guy via reflection as well.

Your other option is to cast the value as dynamic , and then attempt (and hope) your invocations work as expected.

So in your situation, you best bet would be to probably use the dynamic type:

dynamic obj = Propertyinfo.GetValue(myobject);
obj.SomeMethodYouWantToCall(); // and catch DLR errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM