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

后端 未结 6 2167
醉话见心
醉话见心 2021-02-18 22:47

I will start by explaining my scenario in code:

public class A { }

public class B : A { }

public class C : B { }

public class D { }

public c         


        
相关标签:
6条回答
  • 2021-02-18 22:52

    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
    
    0 讨论(0)
  • 2021-02-18 22:57

    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.

    0 讨论(0)
  • 2021-02-18 22:59

    You can just use is:

    if (c is B) // Will be true
    
    if (d is B) // Will be false
    
    0 讨论(0)
  • 2021-02-18 23:00

    This looks like a job for polymorphism, as opposed to a big switch statement with tests for specific classes.

    0 讨论(0)
  • 2021-02-18 23:03
    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.

    0 讨论(0)
  • 2021-02-18 23:12

    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())
    
    0 讨论(0)
提交回复
热议问题