Validating IsAssignableFrom, IsInstanceOf, and BaseType

This is just the type of service locator that I am trying to implement, where I would like to try to register the implementation on an interface to which it does not belong, for example:

public void Add(Type interfaceType, object implementingObject) { // ... check for nulls // NO GOOD if(!implementingObject.GetType().IsAssignableFrom(interfaceType)... // NO GOOD if(!implementingObject.GetType().IsInstanceOf(interfaceType)... // FINALLY! if(!implementingObject.GetType().BaseType.IsAssignableFrom(interfaceType)... // ... ok, add it } 

Now I finally decided to use BaseType.IsInstanceOf by looking at the NUnit isInstanceOf statement, but it still seems inequivalent.

Can someone explain why this makes sense? Is there an easier way to do this?

+4
source share
2 answers

A way to look at it from left to right, as usual, when creating a task in the language.

So, in C #, the equivalent of calling assigningTo.IsAssignableFrom(assigningFrom) (or any of the other methods you mention) should think of it as "will the following code work":

 <assigningTo type> variable = <instance of assigningFrom>; 

When applying this to your code, you want to use:

 interfaceType.IsAssignableFrom(implementingObject.GetType()) interfaceType.IsAssignableFrom(implementingObject.GetType().BaseType) 

The logic is that you want to know if any of the types of the implementation object can assign an interface type or, in other words, if the implementation object can be assigned to an interface.

+4
source

I think you want:

 interfaceType.IsAssignableFrom(implementingObject.GetType()) 

Why can a particular type be assigned from an interface?

0
source

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


All Articles