进行 C# 运行时类型识别的简化方法可以避免 NULL 检查? [英] Streamlined way to do C# run-time type identification that avoids a NULL check?

查看:46
本文介绍了进行 C# 运行时类型识别的简化方法可以避免 NULL 检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己使用了一种常见的运行时类型识别模式,尤其是在编写处理不同类型控件的代码时.这是模式:

I find myself using a common run-time type identification pattern, especially when writing code that handles controls of varying types. Here is the pattern:

if (ctrl is ControlTypeEtc)
    (ctrl as ControlTypeEtc).SomeMethod();

我这样做是为了避免在 as 运算符返回 NULL 的情况下必须进行 NULL 检查.有没有办法将其简化为单个操作?

I do this to avoid having to do a NULL check in case the as operator returns NULL. Is there a way to streamline this to a single operation?

推荐答案

没有办法在一次操作中做到这一点.

No way to do this in a single operation.

但是,使用 as 并检查 null 成本更低,因为只有一种情况,而不是您的代码示例中的两种情况.

However, using as and checking for null is cheaper as there is only one case instead of two as in your code sample.

这篇关于进行 C# 运行时类型识别的简化方法可以避免 NULL 检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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