为什么(string)int32总是抛出:无法将类型'int'转换为'string'

时间:2020-12-17 16:09:13

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'

为什么(string)int32总是抛出:无法将类型'int'转换为'string'

public class Foo
    {   
        private int FooID;
        public Foo()
        {
            FooID = 4;
            string s = (string)FooID; //throws compile error
            string sss = FooID.ToString(); //no compile error
        }
    }

9 个解决方案

#1


Because there is no type conversion defined from Int32 to string. That's what the ToString method is for.

因为没有从Int32到string定义的类型转换。这就是ToString方法的用途。

#2


If you did this:

如果你这样做:

string s = (string)70;

What would you expect to be in s?

你期望在s中做什么?

A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "\x00\x00\x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "\x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.

答:“70”这个数字就像人类读它的方式一样。 B.“+ 70”前面写有正面指示的数字。 C.“F”由ASCII码70表示的字符.D。“\ x00 \ x00 \ x00F”int的四个字节分别转换为它们的ASCII表示。 E.“\ x0000F”将int分成两组,每组两个字节,每个字节代表一个Unicode字符。 F.“1000110”二进制表示为70. G.“$ 70”整数转换为货币H.其他。

The compiler can't tell so it makes you do it the long way.

编译器无法分辨,所以它可以让你做到很长的路要走。

There are two "long ways". The first is to use one of the the Convert.ToString() overloads something like this:

有两个“漫长的道路”。第一种是使用Convert.ToString()重载之一,如下所示:

string s = Convert.ToString(-70, 10);

This means that it will convert the number to a string using base 10 notation. If the number is negative it displays a "-" at the start, otherwise it just shows the number. However if you convert to Binary, Octal or Hexadecimal, negative numbers are displayed in twos complement so Convert.ToString(-7, 16) becomes "ffffffba".

这意味着它将使用基数10表示法将数字转换为字符串。如果数字为负数,则在开头显示“ - ”,否则只显示数字。但是,如果转换为二进制,八进制或十六进制,则负数将以二进制补码显示,因此Convert.ToString(-7,16)变为“ffffffba”。

The other "long way" is to use ToString with a string formatter like this:

另一个“漫长的方法”是使用ToString和字符串格式化程序,如下所示:

string s2 = 70.ToString("D");

The D is a formatter code and tells the ToString method how to convert to a string. Some of the interesting codes are listed below:

D是格式化程序代码,它告诉ToString方法如何转换为字符串。下面列出了一些有趣的代码:

"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I've shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".

“D”十进制格式,如果需要,为数字0-9,开头为“ - ”。例如。 -70变为“-70”。 “D8”我已经显示了8但可能是任何数字。与十进制相同,但它用零填充到所需的长度。例如。 -70变为“-00000070”。插入“N”千位分隔符,最后添加“.00”。例如。 -1000变为“-1,000.00”。 “C”在“ - ”之后的开头添加货币符号,然后它与“N”相同。例如。使用en-Gb培养-1000变为“ - £1,000.00”。 “X”十六进制格式。例如。 -70变成“46”。

Note: These formats are dependent upon the current culture settings so if you are using en-Us you will get a "$" instead of a "£" when using format code "C".

注意:这些格式取决于当前的文化设置,因此如果您使用en-Us,则在使用格式代码“C”时将获得“$”而不是“£”。

For more information on format codes see MSDN - Standard Numeric Format Strings.

有关格式代码的详细信息,请参阅MSDN - 标准数字格式字符串。

#3


When performing a cast operation like (string)30, you're basically telling the computer that "this object is similar enough to the object I'm casting to that I won't lose much (or any) data/functionality".

当执行类似(字符串)30的强制转换操作时,你基本上告诉计算机“这个对象与我正在投射的对象相似,我不会丢失太多(或任何)数据/功能”。

When casting a number to a string, there is a "loss" in data. A string can not perform mathematical operations, and it can't do number related things.

将数字转换为字符串时,数据中存在“丢失”。字符串不能执行数学运算,也不能执行数字相关的操作。

That is why you can do this:

这就是你可以这样做的原因:

int test1 = 34;
double test2 = (double)test1;

But not this:

但不是这个:

int test1 = 34;
string test2 = (string)test1;

This example isn't perfect since (IIRC) the conversion here is implicit, however the idea is that when converting to a double, you don't lose any information. That data type can still basically act the same whether it's a double or an int. The same can't be said of an int to a string.

这个例子并不完美,因为(IIRC)这里的转换是隐含的,但是想法是当转换为double时,你不会丢失任何信息。无论是double还是int,该数据类型仍然可以基本相同。对字符串的int不能说同样的。

Casting is (usually) only allowed when you won't lose much functionality after the conversion is done.

只有在转换完成后您不会失去太多功能时,才允许(通常)进行转换。

The .ToString() method is different from casting because it's just a method that returns a string data type.

.ToString()方法与强制转换不同,因为它只是一个返回字符串数据类型的方法。

#4


Just another note: In general, if you want to do an explicit conversion like this (and I agree with many other answers here as to why it needs to be an explicit conversion) don't overlook the Convert type. It is designed for these sorts of primitive/simple type conversions.

另一个注意事项:一般来说,如果你想做这样的显式转换(我同意这里的许多其他答案,为什么它需要显式转换)不要忽略转换类型。它专为这些原始/简单类型转换而设计。

I know that when starting in C# (and coming from C++) I found myself running into type casts that seemed like they should have worked. C++ is just a bit more liberal when it comes to this sort of thing, so in C# the designers wanted you to know when your type conversion were ambiguous or ill-advised. The Convert type then fills in the gaps by allowing you to explicitly convert and understand the side-effects.

我知道,当从C#开始(并且来自C ++)时,我发现自己遇到了看起来应该有效的类型转换。当涉及到这种事情时,C ++就更加*了,所以在C#中,设计师希望你知道何时你的类型转换模糊或不明智。然后,转换类型允许您显式转换和理解副作用,从而填补空白。

#5


Int doesn't have an explicit operator to string. However, they have Int32.ToString();. Maybe you can create one with Extension methods, if you really want to.

Int没有明确的字符串运算符。但是,他们有Int32.ToString();.如果你真的想要,也许可以使用Extension方法创建一个。

#6


Because C# does not know how to convert int to string, the library (.ToString) does.

因为C#不知道如何将int转换为字符串,所以库(.ToString)可以。

#7


Int32 can't be casted to string because C# compiler doesn't know how to converter from one type to another.

Int32无法转换为字符串,因为C#编译器不知道如何从一种类型转换为另一种类型。

Why is that, you will ask the reason is simple int32 is type integer/numerical and string is, oh well type string/characters. You may be able to convert from numerical type to another numerical type (ex. float to int, but be warned possible loss of accuracy). If all possible casts where coded in the compiler the compiler would become too slow and certainly would miss much of the possible casts created for user defined types which is a major NO NO.

为什么会这样,你会问原因是简单的int32是类型整数/数字和字符串是,哦,好类型字符串/字符。您可以将数字类型转换为另一种数字类型(例如,float到int,但要注意可能会丢失准确性)。如果在编译器中编码的所有可能的强制转换编译器将变得太慢并且肯定会错过为用户定义的类型创建的大部分可能的强制转换,这是一个主要的NO NO。

So the workaround is that any object in C# has a function inherited .ToString() that knows how to handle every type because .ToString() is specifically coded for the specific type, and as you guessed by now returns a string.

所以解决方法是C#中的任何对象都有一个继承.ToString()的函数,它知道如何处理每个类型,因为.ToString()是针对特定类型专门编码的,正如你现在猜测的那样返回一个字符串。

After all Int32 type is some bits in memory (32 bits to be exact) and string type is another pile of bits (how many bits depends on how much has been allocated) the compiler/runtime doesn't know anything just by itself looking at that data until now. .ToString() function accesses the specific metadata needed to convert from one to the other.

在所有Int32类型都是内存中的某些位(确切地说是32位)并且字符串类型是另一堆位(多少位取决于已经分配了多少)之后,编译器/运行时不仅仅知道任何东西本身在看那个数据到现在为止。 .ToString()函数访问从一个转换为另一个所需的特定元数据。

#8


I just found the answer. ToString works fine on an int variable. You just have to make sure you add the brackets.

我刚刚找到了答案。 ToString在int变量上工作正常。你只需要确保添加括号。

ie...

int intMyInt=32;

string strMyString = intMyInt.ToString();

#9


VB .net is perfectly capable of casting from an int to string... in fact so is Java. Why should C# have a problem with it? Sometimes it is necessary to use a number value in calculations and then display the result in a string format. How else would you manage to display the result of a calculation in a TextBox?

VB .net完全能够从int转换为字符串......实际上Java也是如此。为什么C#有问题呢?有时需要在计算中使用数值,然后以字符串格式显示结果。你怎么能设法在TextBox中显示计算结果?

The responses given here make no sense. There must be a way to cast an int as a string.

这里给出的回答毫无意义。必须有一种方法将int转换为字符串。

#1


Because there is no type conversion defined from Int32 to string. That's what the ToString method is for.

因为没有从Int32到string定义的类型转换。这就是ToString方法的用途。

#2


If you did this:

如果你这样做:

string s = (string)70;

What would you expect to be in s?

你期望在s中做什么?

A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "\x00\x00\x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "\x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.

答:“70”这个数字就像人类读它的方式一样。 B.“+ 70”前面写有正面指示的数字。 C.“F”由ASCII码70表示的字符.D。“\ x00 \ x00 \ x00F”int的四个字节分别转换为它们的ASCII表示。 E.“\ x0000F”将int分成两组,每组两个字节,每个字节代表一个Unicode字符。 F.“1000110”二进制表示为70. G.“$ 70”整数转换为货币H.其他。

The compiler can't tell so it makes you do it the long way.

编译器无法分辨,所以它可以让你做到很长的路要走。

There are two "long ways". The first is to use one of the the Convert.ToString() overloads something like this:

有两个“漫长的道路”。第一种是使用Convert.ToString()重载之一,如下所示:

string s = Convert.ToString(-70, 10);

This means that it will convert the number to a string using base 10 notation. If the number is negative it displays a "-" at the start, otherwise it just shows the number. However if you convert to Binary, Octal or Hexadecimal, negative numbers are displayed in twos complement so Convert.ToString(-7, 16) becomes "ffffffba".

这意味着它将使用基数10表示法将数字转换为字符串。如果数字为负数,则在开头显示“ - ”,否则只显示数字。但是,如果转换为二进制,八进制或十六进制,则负数将以二进制补码显示,因此Convert.ToString(-7,16)变为“ffffffba”。

The other "long way" is to use ToString with a string formatter like this:

另一个“漫长的方法”是使用ToString和字符串格式化程序,如下所示:

string s2 = 70.ToString("D");

The D is a formatter code and tells the ToString method how to convert to a string. Some of the interesting codes are listed below:

D是格式化程序代码,它告诉ToString方法如何转换为字符串。下面列出了一些有趣的代码:

"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I've shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".

“D”十进制格式,如果需要,为数字0-9,开头为“ - ”。例如。 -70变为“-70”。 “D8”我已经显示了8但可能是任何数字。与十进制相同,但它用零填充到所需的长度。例如。 -70变为“-00000070”。插入“N”千位分隔符,最后添加“.00”。例如。 -1000变为“-1,000.00”。 “C”在“ - ”之后的开头添加货币符号,然后它与“N”相同。例如。使用en-Gb培养-1000变为“ - £1,000.00”。 “X”十六进制格式。例如。 -70变成“46”。

Note: These formats are dependent upon the current culture settings so if you are using en-Us you will get a "$" instead of a "£" when using format code "C".

注意:这些格式取决于当前的文化设置,因此如果您使用en-Us,则在使用格式代码“C”时将获得“$”而不是“£”。

For more information on format codes see MSDN - Standard Numeric Format Strings.

有关格式代码的详细信息,请参阅MSDN - 标准数字格式字符串。

#3


When performing a cast operation like (string)30, you're basically telling the computer that "this object is similar enough to the object I'm casting to that I won't lose much (or any) data/functionality".

当执行类似(字符串)30的强制转换操作时,你基本上告诉计算机“这个对象与我正在投射的对象相似,我不会丢失太多(或任何)数据/功能”。

When casting a number to a string, there is a "loss" in data. A string can not perform mathematical operations, and it can't do number related things.

将数字转换为字符串时,数据中存在“丢失”。字符串不能执行数学运算,也不能执行数字相关的操作。

That is why you can do this:

这就是你可以这样做的原因:

int test1 = 34;
double test2 = (double)test1;

But not this:

但不是这个:

int test1 = 34;
string test2 = (string)test1;

This example isn't perfect since (IIRC) the conversion here is implicit, however the idea is that when converting to a double, you don't lose any information. That data type can still basically act the same whether it's a double or an int. The same can't be said of an int to a string.

这个例子并不完美,因为(IIRC)这里的转换是隐含的,但是想法是当转换为double时,你不会丢失任何信息。无论是double还是int,该数据类型仍然可以基本相同。对字符串的int不能说同样的。

Casting is (usually) only allowed when you won't lose much functionality after the conversion is done.

只有在转换完成后您不会失去太多功能时,才允许(通常)进行转换。

The .ToString() method is different from casting because it's just a method that returns a string data type.

.ToString()方法与强制转换不同,因为它只是一个返回字符串数据类型的方法。

#4


Just another note: In general, if you want to do an explicit conversion like this (and I agree with many other answers here as to why it needs to be an explicit conversion) don't overlook the Convert type. It is designed for these sorts of primitive/simple type conversions.

另一个注意事项:一般来说,如果你想做这样的显式转换(我同意这里的许多其他答案,为什么它需要显式转换)不要忽略转换类型。它专为这些原始/简单类型转换而设计。

I know that when starting in C# (and coming from C++) I found myself running into type casts that seemed like they should have worked. C++ is just a bit more liberal when it comes to this sort of thing, so in C# the designers wanted you to know when your type conversion were ambiguous or ill-advised. The Convert type then fills in the gaps by allowing you to explicitly convert and understand the side-effects.

我知道,当从C#开始(并且来自C ++)时,我发现自己遇到了看起来应该有效的类型转换。当涉及到这种事情时,C ++就更加*了,所以在C#中,设计师希望你知道何时你的类型转换模糊或不明智。然后,转换类型允许您显式转换和理解副作用,从而填补空白。

#5


Int doesn't have an explicit operator to string. However, they have Int32.ToString();. Maybe you can create one with Extension methods, if you really want to.

Int没有明确的字符串运算符。但是,他们有Int32.ToString();.如果你真的想要,也许可以使用Extension方法创建一个。

#6


Because C# does not know how to convert int to string, the library (.ToString) does.

因为C#不知道如何将int转换为字符串,所以库(.ToString)可以。

#7


Int32 can't be casted to string because C# compiler doesn't know how to converter from one type to another.

Int32无法转换为字符串,因为C#编译器不知道如何从一种类型转换为另一种类型。

Why is that, you will ask the reason is simple int32 is type integer/numerical and string is, oh well type string/characters. You may be able to convert from numerical type to another numerical type (ex. float to int, but be warned possible loss of accuracy). If all possible casts where coded in the compiler the compiler would become too slow and certainly would miss much of the possible casts created for user defined types which is a major NO NO.

为什么会这样,你会问原因是简单的int32是类型整数/数字和字符串是,哦,好类型字符串/字符。您可以将数字类型转换为另一种数字类型(例如,float到int,但要注意可能会丢失准确性)。如果在编译器中编码的所有可能的强制转换编译器将变得太慢并且肯定会错过为用户定义的类型创建的大部分可能的强制转换,这是一个主要的NO NO。

So the workaround is that any object in C# has a function inherited .ToString() that knows how to handle every type because .ToString() is specifically coded for the specific type, and as you guessed by now returns a string.

所以解决方法是C#中的任何对象都有一个继承.ToString()的函数,它知道如何处理每个类型,因为.ToString()是针对特定类型专门编码的,正如你现在猜测的那样返回一个字符串。

After all Int32 type is some bits in memory (32 bits to be exact) and string type is another pile of bits (how many bits depends on how much has been allocated) the compiler/runtime doesn't know anything just by itself looking at that data until now. .ToString() function accesses the specific metadata needed to convert from one to the other.

在所有Int32类型都是内存中的某些位(确切地说是32位)并且字符串类型是另一堆位(多少位取决于已经分配了多少)之后,编译器/运行时不仅仅知道任何东西本身在看那个数据到现在为止。 .ToString()函数访问从一个转换为另一个所需的特定元数据。

#8


I just found the answer. ToString works fine on an int variable. You just have to make sure you add the brackets.

我刚刚找到了答案。 ToString在int变量上工作正常。你只需要确保添加括号。

ie...

int intMyInt=32;

string strMyString = intMyInt.ToString();

#9


VB .net is perfectly capable of casting from an int to string... in fact so is Java. Why should C# have a problem with it? Sometimes it is necessary to use a number value in calculations and then display the result in a string format. How else would you manage to display the result of a calculation in a TextBox?

VB .net完全能够从int转换为字符串......实际上Java也是如此。为什么C#有问题呢?有时需要在计算中使用数值,然后以字符串格式显示结果。你怎么能设法在TextBox中显示计算结果?

The responses given here make no sense. There must be a way to cast an int as a string.

这里给出的回答毫无意义。必须有一种方法将int转换为字符串。