这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
这可能是微不足道的,但我想不出更好的方法来做到这一点。我有一个COM对象,返回一个变成c#对象的变量。我能把它变成int型的唯一方法是
int test = int.Parse(string.Format("{0}", myobject))
有更干净的方法吗?谢谢
当前回答
你有几个选择:
(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)可能会工作,并建议您检查调试器以找出实际的运行时类型。
其他回答
你可以先将object转换为string,然后将string转换为int; 例如:
string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);
这对我很管用。
Convert.ToInt32(myobject);
这将处理myobject为null并返回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
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
使用Int32。TryParse如下。
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}