最快(最佳)方式转换为int [英] Quickest (best) way to convert to an int
问题描述
朋友们,
只是有关类型转换的一个小问题.将对象转换为整数的最佳方法是什么?
例如,如果我使用存储过程从SQL Server检索整数,则使用SqlCommand的ExecuteScalar()方法:
Hey friends,
Just a small question about type conversions. What is the best way to convert an object to an integer?
For example, if I retrieve an integer from SQL Server using a Stored Procedure, I use the SqlCommand''s ExecuteScalar() method :
object spResult = SqlCommand.ExecuteScalar();
现在,我(漂亮)确保spResult变量为null或包含整数,因为我的存储过程从我的数据源返回了一个int字段.
如果我想将spResult转换为int,我可以使用int.Parse(spResult.ToString());
或int.TryParse(spResult.ToString(), out resultInteger);
,但是我有种感觉,那就不是整洁的方法.
你们觉得呢?
谢谢! Eduard
Now i''m (pretty) sure that the spResult variable either is null or contains an integer since my Stored Procedure returns a single int field from my datasource.
If I want to convert the spResult to an int I either use int.Parse(spResult.ToString());
or int.TryParse(spResult.ToString(), out resultInteger);
but I have a feeling that this is not the neat way.
What do you guys think?
Thanks! Eduard
推荐答案
如果spResult可以包含null或Int类型,那么我宁愿使用
If the spResult can contain either null or of type Int, then i would prefer to use
Nullable<int>
这是链接: http://www.jaltiere.com/index.php/2006/07/24/net-nullable-data-types/ [
Here is the link : http://www.jaltiere.com/index.php/2006/07/24/net-nullable-data-types/[^]
有:
There''s:
int value = (int)spResult;
int value = spResult as Int32;
int value = Convert.ToInt32(spResult);
如果您不确定要从该方法获取int,则应使用
If you''re not sure you''re going to get an int from the method, you should use
int value;
if (!int.TryParse(spResult, out value))
{
throw new Exception("Not an int");
return;
}
我真的不确定哪个更好.我过去曾经用过:
I''m really not sure what''s better. I''ve used this in the past:
int spResult = SqlCommand.ExecuteScalar() as int;
另一方面,MSDN使用这样的演员表:
MSDN on the other hand uses a cast like this:
int spResult = (int)SqlCommand.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx [ ^ ]
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx[^]
这篇关于最快(最佳)方式转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!