大多数情况下,当您想要更改类型时,您只想使用传统的强制转换。
var value = (string)dictionary[key];
这很好,因为:
- 速度很快
- 如果出现问题它会提示(而不是给出 object is null 异常)
那么什么是使用 as
的好例子?我真的找不到或想不出适合它的东西?
注意:实际上,我认为有时编译器会阻止使用 as
有效的强制转换(与泛型相关?)。
最佳答案
当有效对象不是您想要的类型时,使用as
,如果是,您希望采取不同的行动。例如,在某种伪代码中:
foreach (Control control in foo)
{
// Do something with every control...
ContainerControl container = control as ContainerControl;
if (container != null)
{
ApplyToChildren(container);
}
}
或者 LINQ to Objects 中的优化(很多这样的例子):
public static int Count<T>(this IEnumerable<T> source)
{
IList list = source as IList;
if (list != null)
{
return list.Count;
}
IList<T> genericList = source as IList<T>;
if (genericList != null)
{
return genericList.Count;
}
// Okay, we'll do things the slow way...
int result = 0;
using (var iterator = source.GetEnumerator())
{
while (iterator.MoveNext())
{
result++;
}
}
return result;
}
所以使用 as
就像 is
+ 强制转换。根据上述示例,它几乎总是之后与无效检查一起使用。
关于c# - 什么时候应该在 C# 中使用 as 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7566212/