更好的施展对象为int的方式 [英] Better way to cast object to int

查看:87
本文介绍了更好的施展对象为int的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是微不足道的,但我想不出更好的方式来做到这一点。我有一个返回变成在C#中的对象变体的COM对象。我可以进入一个int这一点的唯一方法是

This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is

int test = int.Parse(string.Format("{0}", myobject))

有一个更清洁的方式做到这一点?谢谢

Is there a cleaner way to do this? Thanks

推荐答案

您有几种选择:


  • (INT)—铸造运营商。如果工作对象的已经为的在继承层次一定程度或整数,如果有定义的隐式转换。

  • (int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.

int.Parse()/ int.TryParse()—对于来自未知格式的字符串转换。

int.Parse()/int.TryParse() — For converting from a string of unknown format.

int.ParseExact()/ int.TryParseExact()—在一个特定的格式从字符串转换

int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format

Convert.ToInt32()—对于转换未知类型的对象。它将使用是否有任何明确定义和隐式转换或IConvertible实现。

Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.

为int &MDASH?;请注意,?。在运营商仅作参考类型,所以我用?来表示一个可空< INT> 。在操作符如 Convert.To ____(),但想到的TryParse() ,而不是解析():返回,而不是如果转换抛出一个异常失败。

as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.

这些,我想preFER (INT)如果对象真的只是一个盒装的整数。否则,使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.convert.toint32.aspx\"><$c$c>Convert.ToInt32()在这种情况下

Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.

请注意,这是一个非常的一般的答案:我想抛出一些注意达伦 - 克拉克的回应,因为我觉得它做得很好解决的细节的这里,但回来晚了,并没有投票,以及还没有。他得到我的接受的答案投票,无论如何,对于还建议(INT),用于指出,如果失败(INT)(短)可能的工作,而是和对于建议你检查你的调试器来找出实际的运行时类型。

Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.

这篇关于更好的施展对象为int的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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