【问题标题】:Is there ever a reason to use is versus as? [duplicate]有没有理由使用 is 与 as ? [复制]
【发布时间】:2015-06-23 21:17:01
【问题描述】:

在考虑 C# 中的 isas 时,您可以使用其中任何一个来确认一个类型是否可以转换为另一种类型。

// 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 检查一次,并且它们都对它们支持的转换类型有相同的限制,是否有使用is 的令人信服的理由?

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

【问题讨论】:

  • 你有没有查看过 msdn 网站上关于如何使用 IS 和 AS 安全投射的内容 msdn.microsoft.com/en-us/library/cc488006.aspx the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it.
  • 我了解如何使用这两个运算符来安全地转换类型。我更怀疑是否有令人信服的理由使用is 而不是as
  • 我不认为is 转换类型,它只检查它。 as 投射它。
  • 我也了解这两个运营商的工作。我问如果is 检查类型两次而不是检查一次as,是否有理由使用is

标签: c# type-conversion


【解决方案1】:

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

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
}

【讨论】:

  • 哦!嗯,这清楚了。谢谢。 :)
  • @jdphenix 如果您只是在验证对象的类型而不是使用 castes 对象,那么使用 is 运算符会使您的程序更具可读性。
【解决方案2】:

is 运算符执行类型检查。 as 运算符执行类型检查和(如果可能)强制转换。

是否有令人信服的理由使用is

我可以想到几个场景。首先,正如this answer 已经指出的那样,您不能 as-cast 不可为空的值类型。

但是您的原始示例虽然非常常见,但严重偏向as。这一切都取决于您在演员表和/或类型检查之后要做什么。

假设如果你的转换成功,你将调用以下方法:

private void PerformManagerDuty(Manager m) 
{
    //Stuff happens
}

执行as 强制转换,然后空检查需要比is 多一行代码:

//as casting with null check
var m = e as Manager; 
if (m != null)
{
    PerformManagerDuty(m);
}

//is check before cast
if (e is Manager)
{ 
    PerformManagerDuty((Manager)e);
}

此外,如果您愿意,在使用 is 执行类型检查后,您可以执行 as 强制转换,而不会造成性能损失:

if (e is Manager)
{ 
    PerformManagerDuty(e as Manager);
}

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 1970-01-01
    • 2010-11-03
    • 2012-04-05
    • 1970-01-01
    • 2016-09-02
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多