C#.NET – 如何获取typeof()来处理继承?
发布时间:2020-12-15 06:45:50 所属栏目:百科 来源:网络整理
导读:我将从代码中解释我的场景: 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 Te
我将从代码中解释我的场景:
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.) 但是我需要的是某种情况,将会考虑到这一点.我如何知道一个对象是一个B还是从它派生的东西? 我不在乎是否是从B派生的对象,只要B类就在那里.我无法预料我的应??用程序中可能出现什么派生类.我只需要假设未来派生类可能存在,因此我只能专注于确保基类是我期待的. 我需要一个能为我执行这个检查的条件.这怎么可以实现? 解决方法
你可以使用是:
if (c is B) // Will be true if (d is B) // Will be false (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |