C#.NET - 如何让typeof()与继承一起工作? [英] C#.NET - How can I get typeof() to work with inheritance?

查看:126
本文介绍了C#.NET - 如何让typeof()与继承一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将首先在代码中解释我的情景:

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
    }
}

需要注意的重点是:

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

我相信这个实际上将评估为假,因为(B)类型和(C)类型在两个方向上彼此不相等。 (C是B,但B不一定是C。)

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.)

但我需要的是某种条件会考虑到这一点。如何判断一个对象是B还是从它派生的任何东西?

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?

我不在乎它是否是来自B的对象DERIVED,只要基数B级就在那里。而且我无法预测派生类可能会在我的应用程序中显示出来。我只需要假设将来可能存在未知的派生类 - 因此我只能专注于确保基类是我所期望的。

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?

推荐答案

你可以使用

if (c is B) // Will be true

if (d is B) // Will be false

这篇关于C#.NET - 如何让typeof()与继承一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆