![newCards newCards]()
本文介绍了关于铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 你好! 这里我有两种不同的方式来使用演员。 这些中的任何一种都比另一种好吗? 或者只是一个品味问题。 newCards.Add((Card)sourceCard.Clone()); newCards.Add( sourceCard.Clone()as Card); // TonyHello!Here I have two different way to use casting.Is any of these any better then the other?Or is it just a question of taste.newCards.Add((Card)sourceCard.Clone());newCards.Add(sourceCard.Clone() as Card);//Tony推荐答案 使用" as"如果演员表失败则不会抛出异常 - 它只是 会返回null。 使用直接演员也允许用户定义的转换等。 我倾向于使用as;对于价值观我很怀疑 - 当我即将 测试结果时: 对象未知= GetMeSomeData(); string text = unknown as string; if(text!= null) { ... } 我真正使用直接投射,真的希望它成功 - 例如当故障表明存在问题时应该报告为 例外: 对象shouldBeString = GetMeSomeText(); string text =(string)shouldBeString; - Jon Skeet - < sk *** @ pobox.com> 网站: http://www.pobox.com/~skeet 博客: http://www.msmvps.com/jon.skeet C#深度: http://csharpindepth.comUsing "as" doesn''t throw an exception if the cast fails - it justreturns null instead.Using a direct cast also allows for user-defined conversions etc.I tend to use "as" for values I''m in doubt about - when I''m about totest the result:Object unknown = GetMeSomeData();string text = unknown as string;if (text != null){...}I use direct casting when I really, really expect it to succeed - i.e.when a failure indicates a problem which should be reported as anexception:Object shouldBeString = GetMeSomeText();string text = (string) shouldBeString;--Jon Skeet - <sk***@pobox.com>Web site: http://www.pobox.com/~skeetBlog: http://www.msmvps.com/jon.skeetC# in Depth: http://csharpindepth.com 这篇关于关于铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-31 19:54