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

Categories

While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC:

if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }

this seems to me a pretty convoluted way of basically writing

if(controllerType is IController) { ... }

I appreciate there are subtle differences between is and IsAssignableFrom, ie IsAssignableFrom doesn't include cast conversions, but I'm struggling to understand the implication of this difference in practical scenarios.

When is it imporantant to choose IsAssignableFrom over is? What difference would it make in the GetControllerExample?

if (!typeof(IController).IsAssignableFrom(controllerType))
      throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;
See Question&Answers more detail:os

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

1 Answer

It's not the same.

if(controllerType is IController)

would always evaluate to false since controllerType is always a Type, and a Type is never an IController.

The is operator is used to check whether an instance is compatible to a given type.

The IsAssignableFrom method is used to check whether a Type is compatible with a given type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...