是否有理由使用 is 与 as? [英] Is there ever a reason to use is versus as?

查看:35
本文介绍了是否有理由使用 is 与 as?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当考虑 C# 中的 isas 时,您可以使用两者之一来确认一种类型是否可以转换为另一种类型.

When considering the is versus as in C#, you can use either to confirm if a type is convertible to another type.

// using is
Employee e = new Manager();
if (e is Manager) { 
    var m = (Manager) e; 
    // m is now type `Manager`
}

// using as
Employee e = new Manager(); 
Manager m = e as Manager; 
// m is now type `Manager`
if (m != null) { 

}

我了解这两个运算符的工作原理以及如何使用它们.考虑 is 运算符检查类型两次而 as 检查一次,并且它们都对支持的转换类型具有相同的限制,是否有令人信服的理由使用?

I understand how both operators work and how to use them. Consider the is operator checks the type twice while as checks once, and they both have the same restrictions regarding what types of conversions they support, is there ever a compelling reason to use is?

标记的重复是询问两个运算符之间的区别是什么.我的问题是专门询问了解两者的作用,为什么使用 is?"他们不是同一个问题,也没有相同的答案.

The marked duplicate is asking what is the difference between the two operators. My question is specifically asking "Understanding what both do, why use is?" They are not the same question, nor do they have the same answer.

推荐答案

当目标类型是不可为空的值类型时,您必须使用 is 而不是 as:

You must use is instead of as when the destination type is a non-nullable value type:

object obj = 0;
int i = obj as int; // compilation error because int can't represent null

if (obj is int)
{
    int j = (int)obj; // works
}

这篇关于是否有理由使用 is 与 as?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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