为什么使用 TryCast 而不是 DirectCast? [英] Why use TryCast instead of DirectCast?

查看:29
本文介绍了为什么使用 TryCast 而不是 DirectCast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将 Object obj 转换为 Type T 时,如果无法转换,则说明有问题.

When I am trying to cast Object obj to Type T, if it can not be cast then there is something wrong.

在我投射对象后,我将寻找使用投射对象的方法.

And after I cast the object I will be looking for working with the cast object.

与其说我将在何处使用该对象,不如说我期望在我将要投射它的地方得到一个异常.

Rather I will be expecting to get an exception at the place where I will be casting it than say where I will be using that object.

从这个意义上说,使用 DirectCast 而不是 TryCast 更好吗?还是我错过了使用 TryCast 的其他意义?

In this sense, is it better to use DirectCast instead of TryCast? Or am I missing some other significance of using TryCast?

推荐答案

(对于 C# 开发者来说,TryCast 类似于as",DirectCast 相当于普通的强制转换.正如 Mike 在评论中指出的那样,as"适用于可空值类型,但 TryCast 不适用.)

(For C# developers, TryCast is similar to "as" and DirectCast is the equivalent of normal casting. As Mike pointed out in the comments, "as" works for nullable value types, but TryCast doesn't.)

如果值真的应该是 T,那么 DirectCast 确实是正确的方法 - 它会很快失败,并带有适当的错误.

If the value really should be a T, then DirectCast is indeed the right way to go - it fails fast, with an appropriate error.

TryCast 在目标为错误"类型是合法的情况下是合适的.例如,要获取容器中的所有 Button 控件,您可以遍历控件集合并尝试将每个控件强制转换为 Button.如果它有效,你就用它做一些事情——如果它不起作用,你继续前进.(对于 LINQ,您可以为此使用 OfType,但您明白我的意思...)

TryCast is appropriate when it's legitimate for the target to be the "wrong" type. For instance, to get all the Button controls in a container, you could go through the control collection and try to cast each to Button. If it works, you do something with it - if it doesn't, you move on. (With LINQ you can just use OfType for this purpose, but you see what I mean...)

根据我的经验,直接强制转换比 TryCast 更合适 - 尽管对于泛型,我发现自己的强制转换次数比以前少了很多.

In my experience direct casting is appropriate more often than TryCast - although with generics I find myself casting a lot less often than I used to anyway.

这篇关于为什么使用 TryCast 而不是 DirectCast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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