这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个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。

在这两种情况下都要注意例外情况。

使用Int32。TryParse如下。

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;

奇怪,但是公认的答案似乎是错误的,因为从我的测试和阅读文档来看,它不应该考虑隐式或显式操作符。

因此,如果我有一个object类型的变量,并且“boxed”类定义了一些隐式操作符,它们将不起作用。

相反,另一种简单的方法,但真正的性能成本是在动态中转换。

(国际)(动态)我的对象。

你可以在VS的交互窗口中尝试。

public class Test
{
  public static implicit operator int(Test v)
  {
    return 12;
  }
}

(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
Convert.ToInt32(myobject);

这将处理myobject为null并返回0的情况,而不是抛出异常。