gpt4 book ai didi

c# - "is"- 类型运算符

转载 作者:太空狗 更新时间:2023-10-29 20:51:58 25 4
gpt4 key购买 nike

我使用“is”运算符来查找某个类:

for(int i=0; i<screens.Count; i++){
if(screen is ScreenBase){
//do something...
}
}

这工作得很好,尤其是当它找到任何继承自 ScreenBase 的类而不是 ScreenBase 的基类时。

当我只知道类型并且不想实例化类时,我想做同样的事情:

Type screenType = GetType(line);
if (screenType is ScreenBase)

但此比较会产生警告,因为它将与“Type”类进行比较。

我知道的唯一选择是与 ==typeof 进行比较,但这只会测试确切的类型而不是继承的类型。有没有办法获得类似于"is"运算符的类似行为,但对于类型类描述的类型?

最佳答案

The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?

如果 GetType(line) 返回一个类型(顺便说一句,我会推荐一个更好的名称),您可以使用 Type.IsAssignableFrom :

if (typeof(ScreenBase).IsAssignableFrom(GetType(line)))
{
}

关于c# - "is"- 类型运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com