简体   繁体   中英

C#.NET - How can I get typeof() to work with inheritance?

I will start by explaining my scenario in code:

public class A { }

public class B : A { }

public class C : B { }

public class D { }

public class Test
{
    private A a = new A ( ) ;
    private B b = new B ( ) ;
    private C c = new C ( ) ;
    private D d = new D ( ) ;

    public Test ( )
    {
        // Evaluates to "false"
        if ( a.GetType == typeof(B) ) { } //TODO: Add Logic

        // Evaluates to "true"
        if ( b.GetType == typeof(B) ) { } //TODO: Add Logic

        // I WANT this to evaluate to "true"
        if ( c.GetType == typeof(B) ) { } //TODO: Add Logic

        // Evaluates to "false"
        if ( d.GetType == typeof(B) ) { } //TODO: Add Logic
    }
}

The important line to take notice of here is:

if ( c.GetType == typeof(B) ) { }

I believe that this will in fact evaluate to "false", since typeof(B) and typeof(C) are not equal to each other in both directions. (C is a B, but B is not necessarily a C.)

But what I need is some kind of condition that will take this into account. How can I tell if an object is a B or anything derived from it?

I don't care if it is an object DERIVED from B, so long as the base B class is there. And I can't anticipate what derived class might show up in my application. I just have to assume that unkown derived classes may exist in the future - and therefore I can only focus on making sure that the base class is what I am expecting.

I need a condition that will perform this check for me. How can this be accomplished?

You can just use is :

if (c is B) // Will be true

if (d is B) // Will be false

Edit: this answers the question in the thread title. cdm9002 has the better answer to the problem as described in the full post.

typeof(B).IsAssignableFrom(c.GetType())

这看起来像是一个多态性的工作,而不是一个带有特定类测试的大型switch语句。

As an alternative to the (c is B) check, you can also do the following:

var maybeB = c as B;
if (maybeB != null) {
   // make use of maybeB
}

This is preferred in some cases since in order to make use of c as a B when using is , you would have to cast anyway.

For VB.NET with Visual Studio 2008, you can check it like:

'MyTextBox control is inherited by Textbox
If Ctl.GetType.Name = "MyTextBox" then    

End If
typeof(B).IsInstanceOfType(c)

Similar to the answer above from sam-harwell, sometimes you may have the type "B" in a variable, so you need to use reflection rather than the "is" operator.

I used Sam's solution, and was pleasantly surprised when Resharper made this suggestion.

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