简体   繁体   中英

IsAssignableFrom, IsInstanceOf and BaseType testing

It's just a service locater type of pattern I am trying to implement, where I'd like to catch an attempt to register an implementation to an interface it doesn't belong to, as in:

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 finaly figured out to use BaseType.IsInstanceOf by looking inside NUnit's isInstanceOf assertion, but it still seems unituitive.

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

The way to look at it is from left to right, like you would normally when making an assignment in a language.

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

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

Applying that to your code, you want to use:

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

The logic being you want to see if any of the types on the implementing object can be assigned to the interface type, or, in other words, if the implementing object can be assigned to interfaceType.

I think you want:

interfaceType.IsAssignableFrom(implementingObject.GetType())

Why would a concrete type be assignable from an interface?

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