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

后端 未结 6 2164
醉话见心
醉话见心 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: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.

提交回复
热议问题