简体   繁体   中英

Generic type inference with a derived type

class Property is 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 this way, the type that's inferred is Property, and not the more derived Well , or RealEstate , presumably because the type inference is being done at compile time. I've worked around this by casting P to dynamic , like:

var PropertyInfoPortion = getPropertyEditPortion((dynamic)P);

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

EDIT

Sorry, I always try to show the least amount of code to get the point across so things don't 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 Property (which is abstract) and I was using type inference to get the true type to pass to my IoC, without having to resort to reflection (to put together the right generic type). I was just wondering if there was a trick whereby this could be done without dynamic casting, but I guess not. Thanks all.

EDIT 2

I'm trying to create a IPortionOfPropertyInfoAddEditView<T>

My Property instance, P, is of the type that IPortionOfPropertyInfoAddEditView needs, but it's typed as Property, not the more derived type. I would just love it if I could say:

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

But that's obviously not allowed. I figured type inference with a dynamic cast would be the next best thing, I just was wondering if anyone had a better way. Sorry for not being clear from the start!

There is no way to do it with generics, as generics always operate on the static type of values. The fact that you worked around this by using a runtime mechanism ( dynamic ) is a good hint for this.

There are a number of good runtime solutions, but it depends on what exactly you want to do with property (ie, which members you want to access, the visibility of said members, etc).

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

Then, you wouldn't need to care what the derived type of P is in this case, you simply invoke your method, and the correct implementation gets run.

If that's not really feasible, then using the dynamic keyword seems appropriate.

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