Derivation of a generic type with a derived type

class Property - abstract

I have the following method:

 private IPortionOfPropertyInfoAddEditView<T> getPropertyEditPortion<T>(T property) where T : Property { /*details unimportant*/ } Property P = PropertyFactoryMethod.GetSomePropertyInstance(); var PropertyInfoPortion = getPropertyEditPortion(P); 

When I call the method in this way, the type that displays this property, and not the more derived Well or RealEstate , seems to be because the type inference is executed at compile time. I worked on this, dropping P to dynamic , for example:

 var PropertyInfoPortion = getPropertyEditPortion((dynamic)P); 

which works great. I'm just wondering if there is a more elegant way to do this.

EDIT

Sorry, I always try to show the least amount of code in order to understand the essence, so that things do not get too cluttered. Here's the full method:

  private IPortionOfPropertyInfoAddEditView<T> getPropertyEditPortion<T>(T property) where T : Property { return StructureMap.ObjectFactory.GetInstance<IPortionOfPropertyInfoAddEditView<T>>(); } 

I have an instance of a property (which is abstract), and I used type inference to get the true type to go to my IoC without resorting to reflection (to assemble the correct generic type). I'm just wondering if there is a trick by which this could be done without dynamic castings, but I think not. Thanks to everyone.

EDIT 2

I am trying to create an IPortionOfPropertyInfoAddEditView<T>

The My Property, P, is of the type that IPortionOfPropertyInfoAddEditView requires, but is typed as a property, not a more derived one. I would just like it if I could say:

 StructureMap.ObjectFactory.GetInstance<IPortionOfPropertyInfoAddEditView<typeof(P)>>() 

But this is clearly not allowed. I decided that type inference with dynamic drive would be the next best thing, I'm just wondering if anyone has a better way. Sorry for the fact that you did not understand from the very beginning!

+4
source share
2 answers

There is no way to do this with generics, since generics always work with a static value type. The fact that you worked on this with the runtime mechanism ( dynamic ) is good advice for this.

There are many good runtime solutions, but it depends on what exactly you want to do with the property (that is, who you want to access with, visibility of the specified members, etc.).

+5
source

The first thing that comes to mind is to make the implementation of the getPropertyEditPortion method of the Property class.

Then you do not need to worry about which derived type P in this case, you just call your method and run the correct implementation.

If this is not realistic, then using the dynamic keyword seems appropriate.

+2
source

Source: https://habr.com/ru/post/1344296/


All Articles