是使用" AS"在C#中铸造一种安全的方式? [英] Is using "as" in C# a safe way of casting?

查看:117
本文介绍了是使用" AS"在C#中铸造一种安全的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如果用关键词为,在下面的代码在C#中铸造的疑惑是一种安全的方式(即不会炸毁):

I am wondering if using the keyword "as" in the following code is a safe way (i.e. won't blow up) of casting in C#:

public void abc(ref Object dataSource)
{
    DataTable table = dataSource as DataTable;
}

如果有铸造一个更安全的方式,请让我知道..我是相当新的C#不知道底细呢!

If there is a safer way of casting, please let me know.. I am fairly new to C# and don't know the ins and outs yet!

谢谢! 。:D

推荐答案

它不会炸毁......但是,这并不一定意味着它是安全的。

It won't blow up... but that doesn't necessarily mean it's safe.

通常当我用引用转换一个演员,这是因为我的真的,真的的认为执行时间类型是一个我指定。如果不是,那表示我的代码中的错误 - 我宁愿本身表现为异常

Typically when I use a cast for a reference conversion, it's because I really, really think that the execution-time type is the one I'm specifying. If it's not, that indicates a bug in my code - and I'd rather that manifested itself as an exception.

如果你有在你的系统坏数据。然后继续仿佛一切都很好是的危险的路径,而不是的安全的路径。这就是方式,将带你,而投将抛出一个 InvalidCastException的,中止无论你之前做的你能引起混乱的坏数据的机会。

If you've got bad data in your system, then continuing as if everything was fine is the dangerous path, not the safe path. That's the way that as will take you, whereas a cast would throw an InvalidCastException, aborting whatever you're doing before you get the chance to cause mayhem with the bad data.

是好的,如果它的有效的为对象不被给定类型的 - 如果它不指示一个错误。您的总是的看到的格局:

as is good if it's valid for the object not to be of the given type - if it doesn't indicate a bug. You almost always see the pattern of:

Foo x = y as Foo;
if (x != null)
{
    ...
}

请参阅有关详细信息, MSDN 什么一样。

See MSDN for more details about what as does.

此外请注意您的可能的不想用 REF 在你的方法。查看传递更多细节参数我文章。大部分如果我看到人们使用的时间 REF 很多,那是因为他们不明白它的真正含义是:)

Note also that you probably don't want to use ref in your method. See my article on parameter passing for more details. Most of the time if I see people using ref a lot, it's because they don't understand what it really means :)

这篇关于是使用" AS"在C#中铸造一种安全的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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