这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
当前回答
还有TryParse。
从MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
其他回答
Convert.ToInt32(myobject);
这将处理myobject为null并返回0的情况,而不是抛出异常。
还有TryParse。
从MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
你有几个选择:
(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() — For converting from a string of unknown format. int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined. 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.
其中,如果对象确实只是一个盒装整数,我更喜欢(int)。否则,在本例中使用Convert.ToInt32()。
请注意,这是一个非常笼统的回答:我想把注意力放在达伦·克拉克的回答上,因为我认为它很好地解决了这里的细节问题,但它来得晚了,还没有被投票。他得到了我对“可接受答案”的投票,无论如何,他还推荐了(int),指出如果失败(int)(short)可能会工作,并建议您检查调试器以找出实际的运行时类型。
int i = myObject.myField.CastTo<int>();
也许Convert.ToInt32。
在这两种情况下都要注意例外情况。