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

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

有更干净的方法吗?谢谢


当前回答

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

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

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

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

其他回答

你可以先将object转换为string,然后将string转换为int; 例如:

string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);

这对我很管用。

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

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

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

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

我列出了每种类型转换方式的不同之处。有什么特定类型的选角可以处理而不可以处理的?

    // object to int
    // does not handle null
    // does not handle NAN ("102art54")
    // convert value to integar
    int intObj = (int)obj;

    // handles only null or number
    int? nullableIntObj = (int?)obj; // null
    Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null

   // best way for casting from object to nullable int
   // handles null 
   // handles other datatypes gives null("sadfsdf") // result null
    int? nullableIntObj2 = obj as int?; 

    // string to int 
    // does not handle null( throws exception)
    // does not string NAN ("102art54") (throws exception)
    // converts string to int ("26236")
    // accepts string value
    int iVal3 = int.Parse("10120"); // throws exception value cannot be null;

    // handles null converts null to 0
    // does not handle NAN ("102art54") (throws exception)
    // converts obj to int ("26236")
    int val4 = Convert.ToInt32("10120"); 

    // handle null converts null to 0
    // handle NAN ("101art54") converts null to 0
    // convert string to int ("26236")
    int number;

    bool result = int.TryParse(value, out number);

    if (result)
    {
        // converted value
    }
    else
    {
        // number o/p = 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);
      }
   }
Convert.ToInt32(myobject);

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