C# Convert.ToInt32 和 (int) 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1608801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:21:23  来源:igfitidea点击:

What is the difference between Convert.ToInt32 and (int)?

c#type-conversion

提问by balalakshmi

The following code throws an compile-time error like

下面的代码抛出一个编译时错误,如

Cannot convert type 'string' to 'int'

无法将类型“字符串”转换为“整数”

string name = Session["name1"].ToString();
int i = (int)name;

whereas the code below compiles and executes successfully:

而下面的代码编译并成功执行:

string name = Session["name1"].ToString();
int i = Convert.ToInt32(name);

I would like to know:

我想知道:

  1. Why does the the first code generate a compile-time error?

  2. What's the difference between the 2 code snippets?

  1. 为什么第一个代码会生成编译时错误?

  2. 2个代码片段有什么区别?

采纳答案by Noldorin

(int)foois simply a cast to the Int32(intin C#) type. This is built into the CLR and requires that foobe a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

(int)foo只是转换为Int32(int在 C# 中) 类型。这是建立在CLR和要求foo是数字变量(例如floatlong等),在这个意义上,它是非常类似于C的投

Convert.ToInt32is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from anyprimitive type to a int(most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

Convert.ToInt32被设计成一个通用的转换函数。它的作用不仅仅是铸造。也就是说,它可以从任何原始类型转换为 a int(最值得注意的是,解析 a string)。您可以在 MSDN 上查看此方法的完整重载列表。

And as Stefan Steigermentions in a comment:

正如Stefan Steiger在评论中提到

Also, note that on a numerical level, (int) footruncates foo(ifoo = Math.Floor(foo)), while Convert.ToInt32(foo)uses half to even rounding(rounds x.5 to the nearest EVEN integer, meaning ifoo = Math.Round(foo)). The result is thus not just implementation-wise, but also numerically notthe same.

另外,请注意,在数字级别上,会(int) foo截断foo( ifoo = Math.Floor(foo)),而Convert.ToInt32(foo)使用一半到偶数舍入(将 x.5舍入到最接近的 EVEN 整数,即ifoo = Math.Round(foo))。因此,结果不仅在实施方面,而且在数字上也不相同。

回答by Arsen Mkrtchyan

1) C# is type safe language and doesn't allow you to assign string to number

1) C# 是类型安全语言,不允许您将字符串分配给数字

2) second case parses the string to new variable. In your case if the Session is ASP.NET session than you don't have to store string there and convert it back when retrieving

2) 第二种情况将字符串解析为新变量。在您的情况下,如果 Session 是 ASP.NET 会话,那么您不必在那里存储字符串并在检索时将其转换回来

int iVal = 5;
Session[Name1] = 5;
int iVal1 = (int)Session[Name1];

回答by Ilya Khaprov

Convert.ToInt32

Convert.ToInt32

    return int.Parse(value, CultureInfo.CurrentCulture);

but (int) is type cast, so (int)"2" will not work since you cannot cast string to int. but you can parse it like Convert.ToInt32 do

但是 (int) 是类型转换的,因此 (int)"2" 将不起作用,因为您不能将字符串转换为 int。但你可以像 Convert.ToInt32 那样解析它

回答by Joseph

The difference is that the first snippet is a cast and the second is a convert. Although, I think perhaps the compiler error is providing more confusion here because of the wording. Perhaps it would be better if it said "Cannot cast type 'string' to 'int'.

不同之处在于第一个片段是强制转换,第二个片段是转换。虽然,我认为由于措辞,编译器错误可能在这里提供了更多的混乱。如果它说“无法将类型'string'转换为'int',也许会更好。

回答by Jerry Bullard

There is not a default cast from string to int in .NET. You can use int.Parse() or int.TryParse() to do this. Or, as you have done, you can use Convert.ToInt32().

.NET 中没有从 string 到 int 的默认转换。您可以使用 int.Parse() 或 int.TryParse() 来执行此操作。或者,正如您所做的那样,您可以使用 Convert.ToInt32()。

However, in your example, why do a ToString() and then convert it back to an int at all? You could simply store the int in Session and retrieve it as follows:

但是,在您的示例中,为什么要执行 ToString() 然后将其转换回 int 呢?您可以简单地将 int 存储在 Session 中并按如下方式检索它:

int i = Session["name1"];

回答by Philip Wallace

A string cannot be cast to an int through explicit casting. It must be converted using int.Parse.

不能通过显式转换将字符串转换为 int。它必须使用int.Parse.

Convert.ToInt32 basically wraps this method:

Convert.ToInt32 基本上包装了这个方法:

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

回答by ecoffey

To quote from this Eric Lippert article:

引用Eric Lippert 的这篇文章

Cast means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is not of the given type; find me an equivalent value that belongs to the given type".

Cast 意味着两个相互矛盾的事情:“检查这个对象是否真的属于这种类型,如果不是,则抛出”和“这个对象不是给定的类型;给我找一个属于给定类型的等效值”。

So what you were trying to do in 1.) is assert that yes a String is an Int. But that assertion fails since String is not an int.

因此,您在 1.) 中尝试做的是断言是的 String 是 Int。但该断言失败,因为 String 不是 int。

The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int. It can still fail, for example:

2.) 成功的原因是因为 Convert.ToInt32() 解析字符串并返回一个 int。它仍然可能失败,例如:

Convert.ToInt32("Hello");

Would result in an Argument exception.

将导致 Argument 异常。

To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.

总而言之,从 String 转换为 Int 是一个框架问题,而不是 .Net 类型系统中隐含的东西。

回答by John K

You're talking about a C# casting operation vs .NET Conversion utilities

您在谈论 C# 转换操作与 .NET 转换实用程序

  • C# Language-level castinguses parenthesis - e.g. (int) - and conversion support for it is limited, relying on implicit compatibility between the types, or explicitly defined instructions by the developer via conversion operators.
  • Many conversion methods exist in the .NET Framework, e.g. System.Convert, to allow conversionbetween same or disparate data types.
  • C# 语言级转换使用括号 - 例如 (int) - 并且对它的转换支持是有限的,依赖于类型之间的隐式兼容性,或者开发人员通过转换运算符显式定义的指令。
  • .NET Framework 中存在许多转换方法,例如System.Convert,以允许在相同或不同的数据类型之间进行转换

(Casting)syntax works on numeric data types, and also on "compatible" data types. Compatible means data types for which there is a relationship established through inheritance (i.e. base/derived classes) or through implementation (i.e. interfaces).

(强制转换)语法适用于数字数据类型,也适用于“兼容”数据类型。兼容是指通过继承(即基类/派生类)或通过实现(即接口)建立关系的数据类型。

Casting can also work between disparate data types that have conversion operatorsdefined.

转换也可以在定义了转换运算符的不同数据类型之间工作。

The System.Convertclass on the other hand is one of many available mechanisms to convert things in the general sense; it contains logic to convert between disparate, known, data types that can be logically changed from one form into another.

另一方面,System.Convert类是许多可用的一般意义上的转换机制之一;它包含在不同的、已知的数据类型之间进行转换的逻辑,这些数据类型可以在逻辑上从一种形式更改为另一种形式。

Conversion even covers some of the same ground as casting by allowing conversion between similar data types.

通过允许类似数据类型之间的转换,转换甚至涵盖了与强制转换相同的一些领域。



Remember that the C# language has its own way of doing some things.
And the underlying .NET Framework has its own way of doing things, apart from any programming language.
(Sometimes they overlap in their intentions.)

请记住,C# 语言有自己的做事方式。
除了任何编程语言之外,底层的 .NET Framework 都有自己的做事方式。
(有时他们的意图重叠。)

Think of casting as a C# language-level feature that is more limited in nature, and conversion via the System.Convert class as one of many available mechanisms in the .NET framework to convert values between different kinds.

将强制转换视为本质上更受限制的 C# 语言级功能,并将通过 System.Convert 类进行的转换视为 .NET 框架中用于在不同类型之间转换值的众多可用机制之一。

回答by Marc Gravell

(this line relates to a question that was merged) You should never use (int)someString- that will never work (and the compiler won't let you).

(这一行与一个被合并的问题有关)你永远不应该使用(int)someString- 那永远不会工作(并且编译器不会让你)。

However, int int.Parse(string)and bool int.TryParse(string, out int)(and their various overloads) are fair game.

然而,int int.Parse(string)bool int.TryParse(string, out int)(以及它们的各种重载)是公平的游戏。

Personally, I mainlyonly use Convertwhen I'm dealing with reflection, so for me the choice is Parseand TryParse. The first is when I expectthe value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to checkif it is a valid integer - I can then decide what to do when it is/isn't.

就我个人而言,我主要Convert在处理反射时使用,所以对我来说选择是ParseTryParse。第一个是当我希望该值是一个有效整数时,并希望它以其他方式抛出异常。第二个是当我想检查它是否是一个有效整数时 - 然后我可以决定当它是/不是时要做什么。

回答by Tim Barrass

Just a brief extra: in different circumstances (e.g. if you're converting a double, &c to an Int32) you might also want to worry about rounding when choosing between these two. Convert.Int32 will use banker's rounding (MSDN); (int) will just truncate to an integer.

只是一个简短的补充:在不同的情况下(例如,如果您将 double, &c 转换为 Int32),您可能还想在这两者之间进行选择时担心四舍五入。Convert.Int32 将使用银行家的舍入(MSDN);(int) 只会截断为整数。