vb.net 为什么使用 TryCast 而不是 DirectCast?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/385714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use TryCast instead of DirectCast?
提问by Biswanath
When I am trying to cast Object obj
to Type T
, if it can not be cast then there is something wrong.
当我尝试转换Object obj
为 Type 时T
,如果无法转换,则说明有问题。
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.
相反,我希望在我将要投射它的地方得到一个异常,而不是说我将在哪里使用该对象。
In this sense, is it better to use DirectCast
instead of TryCast
?
Or am I missing some other significance of using TryCast
?
从这个意义上说,使用DirectCast
而不是更好TryCast
吗?还是我错过了使用的其他意义TryCast
?
回答by Jon Skeet
(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.)
(对于 C# 开发人员,TryCast
类似于“as”,DirectCast
相当于普通的强制转换。正如 Mike 在评论中指出的那样,“as”适用于可空值类型,但TryCast
不适用。)
If the value really should be a T
, then DirectCast
is indeed the right way to go - it fails fast, with an appropriate error.
如果值真的应该是 a T
,那么DirectCast
确实是正确的方法 - 它会快速失败,并出现适当的错误。
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 tryto 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
当目标是“错误”类型是合法的时是合适的。例如,要获取容器中的所有 Button 控件,您可以浏览控件集合并尝试将每个控件强制转换为 Button。如果它有效,你就用它做一些事情——如果它不起作用,你继续前进。(使用 LINQ,您可以仅用OfType
于此目的,但您明白我的意思......)
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
- 虽然使用泛型的频率更高,但我发现自己的铸造频率比以前少得多。
回答by Jon Limjap
The only difference between the two is that, a TryCast
will return a null if it fails, while a DirectCast
will throw an exception.
两者之间的唯一区别是,TryCast
如果失败,a将返回 null,而 aDirectCast
将抛出异常。
These has implications on how you can handle your program. Personally I prefer not having to throw an exception if the possibility of an improper cast (e.g., text input boxes for user input being cast into numeric types) is pretty high.
这些对你如何处理你的程序有影响。如果不正确的转换(例如,用户输入的文本输入框被转换为数字类型)的可能性非常高,我个人更喜欢不必抛出异常。
回答by STW
I think the others have mentioned the times when you should and shouldn't perform "safe casting" (where you ensure that the cast can succeed before risking an exception). If your program does need to perform safe casting then the TryCast
method saves both you and the program some work.
我认为其他人已经提到了您应该和不应该执行“安全转换”的时间(您确保在冒异常风险之前可以成功转换)。如果您的程序确实需要执行安全转换,那么该TryCast
方法可以为您和程序节省一些工作。
I wasn't aware of the TryCast()
function until today, and I feel like a fool for using the 'bad' method of safely casting.
TryCast()
直到今天我才意识到这个功能,我觉得使用安全铸造的“坏”方法是个傻瓜。
If you did not know about the TryCast()
function then you might end up with something like this:
如果你不知道这个TryCast()
函数,那么你最终可能会得到这样的结果:
'' wasteful, the TypeOf and DirectCast calls are redundant
If TypeOf obj Is SomeClass Then
someObj = DirectCast(obj, SomeClass)
'' More code
End If
The problem is that this method actually performs two casts (technically I think they're actually type-checks). Using the TryCast
and checking if the result is Nothing eliminates the 2nd cast and saves needless work.
问题是这种方法实际上执行了两次转换(从技术上讲,我认为它们实际上是类型检查)。使用TryCast
和 检查结果是否为 Nothing 消除了第二次强制转换并节省了不必要的工作。
'' efficient, only one cast is ever performed and there are no InvalidCastExceptions thrown
someObj = TryCast(obj, SomeClass)
If someObj IsNot Nothing Then
'' More code
End If
Following this pattern lets you avoid having to handle expensive exceptions, and efficiently cast to the correct type.
遵循此模式可让您避免处理代价高昂的异常,并有效地转换为正确的类型。
回答by Daniel Paull
If your design mandates that the object passed to you MUSTbe of type T, then assert (as in Debug.Assert) that the cast succeeds in debug builds and run exhaustive unit tests to prove that your implementation follows your design.
如果您的设计要求传递给您的对象必须是 T 类型,则断言(如在 Debug.Assert 中)强制转换在调试构建中成功并运行详尽的单元测试以证明您的实现符合您的设计。
With your design proven and tested, you can perfrom the direct cast knowing that it can never fail.
通过验证和测试您的设计,您可以执行直接演员,知道它永远不会失败。