Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - How to upcast generic type parameters

When I use reflection in this case, the created type can be many generic types.

BaseStepHandler<BaseStepDataModel> activator = (BaseStepHandler<BaseStepDataModel>)Activator.CreateInstance(....);

The created instance can be all childs of BaseStepDataModel.

BaseStepHandler<OneDataModel>
OR
BaseStepHandler<TwoDataModel>

OneDataModel and TwoDataModel are extending BaseStepDataModel.

this is the exception that I get:

Unable to cast object of type '....GlobalOnBoardingStepOneHandler' to type '....BaseStepHandler`1[....BaseStepDataModel]'.

this is the declaration if GlobalOnBoardingStepOneHandler.

public class GlobalOnBoardingStepOneHandler : BaseStepHandler<GlobalOnBoardingStepOneDataModel>{}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem here is you're expecting contravariance covariance for concrete type generic parameters.

Basically, you won't never achieve your goal using a concrete type, but there's a workaround for this.

You can design a marker interface like this:

public interface IBaseStepHandler<out T> // "out" marks T as covariant
   where T : BaseDataModel // Do you have a model base type? ;)
{
     // Declare members here
}

Where I say "declare members here", just declare such members which are part of your concrete base class (I'm talking about "BaseStepHandler").

After that, implement this interface in your base class BaseStepHandler.

Now, you can do what you want:

IBaseStepHandler<BaseDataModel> some = new WhateverBaseStepHandlerClass(); 

// This is possible because T generic parameter is covariant and it can be casted to `BaseDataModel`, or if you don't provide a `T` generic parameter constraint, you could cast it to `IBaseStepHandler<object>` too!

In order to learn more about covariance, follow this link: http://msdn.microsoft.com/en-us/library/ee207183.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...