这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是

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

有更干净的方法吗?谢谢


当前回答

var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;

其他回答

强制转换(int) myobject应该可以工作。

如果这给出了一个无效的强制转换异常,那么可能是因为变量类型不是VT_I4。我打赌,带有VT_I4的变体被转换为盒装int, VT_I2转换为盒装short,等等。

在对盒装值类型进行强制转换时,只能将其强制转换为盒装的类型。 例如,如果返回的变量实际上是VT_I2,那么(int) (short) myObject应该工作。

最简单的方法是检查返回的对象,并在调试器中查看它的类型。还要确保在互操作程序集中,返回值用MarshalAs(UnmanagedType.Struct)标记。

这对我有用,当myobject包含DBNull时也返回0

int i = myobject.ToString().Cast<int>().FirstOrDefault();
Convert.ToInt32(myobject);

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

你有几个选择:

(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)可能会工作,并建议您检查调试器以找出实际的运行时类型。

还有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);
      }
   }