这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
使用Int32。TryParse如下。
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}
还有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) 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
}
奇怪,但是公认的答案似乎是错误的,因为从我的测试和阅读文档来看,它不应该考虑隐式或显式操作符。
因此,如果我有一个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
你可以先将object转换为string,然后将string转换为int; 例如:
string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);
这对我很管用。
这对我有用,当myobject包含DBNull时也返回0
int i = myobject.ToString().Cast<int>().FirstOrDefault();