简体   繁体   English

C# 将类型转换为泛型强类型

[英]C# cast Type to generic strong typed

I'm enumerating my EntityFramework Container properties.我正在枚举我的 EntityFramework Container 属性。 Through reflection I get only DbSet properties.通过反射,我只得到DbSet属性。 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.但是MyRealType在编译时是未知的。 I only get a Type but i can cast it to DbSet<MyrealType> .我只得到一个Type但我可以将它转换为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.您的另一个选择是将该值转换为dynamic ,然后尝试(并希望)您的调用按预期工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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