简体   繁体   English

在c#.net中进行类型转换

[英]type casting in c#.net

i want to know typecasting in c# .net, i have below lines of code. 我想知道C#.net中的类型转换,我有下面的代码行。

int i=4
object o = i // This works properly without any typecasting becausing boxing takes place automatically
string s= i // This does not work, even when the string is also reference type?
string s=(string)i //This also does not work even if i try to typecast the int to string.
string s= Convert.ToString(i); // this works.

so i want to know why string s = i and string s = (string)i does not work and whats the difference in using (string)i, i.ToString(), and Convert.ToString(i) . 所以我想知道为什么string s = i and string s = (string)i不起作用,以及使用(string)i, i.ToString(), and Convert.ToString(i)什么区别。

When it comes to boxing and unboxing, types have explicit and implicit casting. 当涉及装箱和拆箱时,类型具有显式和隐式转换。 So, in some circumstances, it is easy enough for the runtime to allow for implicit conversion between two supported types, say an Int32 to a Double. 因此,在某些情况下,运行时很容易允许在两个支持的类型之间进行隐式转换,例如Int32到Double。 However, there is no implicit or explicit conversion between an integer and a string, because obviously, a string is not an integer (despite the fact that a string can contain characters for an integer). 但是,整数和字符串之间没有隐式或显式转换,因为很明显,字符串不是整数(尽管字符串可以包含整数的字符)。

string s = i; // attempt at implicit cast from Int32 to String, error
object o = i; // all types inherit from Object, so you may implicitly or explicitly cast from Int32 to Object.
s = (string)i; // attempt at explicit cast from Int32 to string, error
s = i.ToString(); // conversion
s = Convert.ToString(i); // conversion

That's where Convert comes to play. 那就是Convert发挥作用的地方。 Convert contains support for attempting to convert known primitives (and types supporting IConvertable ) to another. Convert包含对尝试将已知基元(和支持IConvertable类型) IConvertable为另一个基元的支持。 So, ToString or Convert.ToString would be the preferred methods (ToString and Convert.ToString are virtually synonymous, except that ToString gives you some formatting options). 因此, ToStringConvert.ToString将是首选方法(ToString和Convert.ToString实际上是同义词,除了ToString为您提供一些格式化选项)。

ToString() method is override by each referance which is vitual method in the object class. ToString()方法被每个referance覆盖,这是对象类中的vitual方法。 string calss override that method and provide string value out of this. 字符串calss覆盖该方法,并提供该方法之外的字符串值。

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows. ToString方法的默认实现返回Object类型的完全限定名称,如以下示例所示。

 Object obj = new Object();
      Console.WriteLine(obj.ToString());

// The example displays the following output:
//      System.Object

this behavior is inherited by reference types that do not override the ToString method. 此行为由不覆盖ToString方法的引用类型继承。

Well, string and object - both of them are reference types. 好吧, stringobject - 它们都是引用类型。 However, object is a root type for all .NET types. 但是, object是所有.NET类型的根类型。

When you use such syntax as (string)i , you are trying to use explicit conversion beetween types. 当使用(string)i这样的语法时,您尝试在类型之间使用显式转换。 But this conversion type requires string class to know about all possible argument types. 但是这种转换类型需要string类来了解所有可能的参数类型。

So we have .ToString() method, which can be overriden in any class, and its return value is used as a string represenation of any object. 所以我们有.ToString()方法,可以在任何类中重写,其返回值用作任何对象的字符串表示。

string s = i and string s = (string)i does not work string s = i和string s =(string)我不行

because I is not a string, and type CASTING is a CAST of the type, not a conversion. 因为我不是字符串,而类型CASTING是类型的CAST,而不是转换。 It only works if i contains a string or a subclass of string (which is not possible for strings, but may be for other classes). 它只有在我包含字符串或字符串的子类时才有效(这对于字符串是不可能的,但对于其他类可能是这样)。

whats the difference in using (string)i, i.ToString(), and Convert.ToString(i). 使用(字符串)i,i.ToString()和Convert.ToString(i)的区别是什么。

  • (string) i: cast i to a string, must be assignable. (字符串)i:将i转换为字符串,必须是可分配的。

  • i.ToString(): calls the ToSstring method, which is defiend on System.object, thus available on ALL classes and structs - but returns no sensible content if not overwritten. i.ToString():调用ToSstring方法,该方法在System.object上是defiend,因此可用于所有类和结构 - 但如果不覆盖则不返回合理的内容。

  • Convert.ToString(i): coonverts i to a string. Convert.ToString(i):将i转换为字符串。 THis includes calling a converter which likely just calls ToString on this rare case. 这包括调用一个转换器,在这种罕见情况下,它可能仅调用ToString。

At the end, casting is not aconversion. 最后,铸造不是反转。 for (string) i to work i HAS TO BE A STRING, while convert tries to MAKE it a string. for(string)我工作我是一个字符串,而转换尝试使它成为一个字符串。

You can specify implicit and explicit conversions in .net, the reason that string s = i fails is that there is no built in cast operation for an integer to a string. 您可以在.net中指定隐式和显式转换,字符串s = i失败的原因是没有针对整数转换为字符串的内置强制转换操作。

see this MSDN article on casting for further information 有关详细信息,请参阅此MSDN有关转换的文章

string s= i does not work because the types don't match, int won't go into a string. string s= i不起作用,因为类型不匹配,int不会进入字符串。

string s=(string)i does not work because it cannot asume which type conversion is to be used (ie which base) string s=(string)i不起作用,因为它无法确定要使用哪种类型转换(即哪个基数)

something like s = ""+i would work on the other hand as it would asume base 10 conversion. 另一方面,像s = ""+i这样s = ""+i东西也可以工作,因为它假定以10为基数的转换。

so i want to know why string s = i and string s = (string)i does not work 所以我想知道为什么string s = istring s = (string)i不起作用

The short answer is that there is no implict (first example above) nor explicit (second example above) cast from int to string defined. 简短的回答是没有任何暗示(上面的第一个例子),也没有明确的(上面的第二个例子)从int定义到字符串。 Slightly longer answer; 答案稍长; when authoring the struct Int32 in C# no casting behaviour was programmed to enable the developer to automagically cast from an int to a string 在C#中创建结构Int32 ,没有编译任何转换行为,使开发人员能够从int自动转换为字符串

whats the difference in using (string)i , i.ToString() , and Convert.ToString(i) 使用(string)ii.ToString()Convert.ToString(i)的区别是什么

Well, the first doesn;t work as you said, and as ive explained above. 好吧,第一个方法不起作用,正如您所说的,正如我在IVE中所述。 The second calls the ToString method on the struct Int32 , which returns (as the name implies) a string representation of the object. 第二个调用结构Int32上的ToString方法,它返回(顾名思义)对象的字符串表示。 It should be noted that this is a brand new string, not in any way related to the original value. 应当注意,这是一个全新的字符串,与原始值没有任何关系。 The third example Convert.ToString will, under the hood, call whatever the most appropriate way to turn the parameter passed in to a string - most likely just calls the ToString method - so pretty much identical to example 2. 第三个例子Convert.ToString将在引擎盖下调用任何最合适的方式来将传入的参数转换为字符串 - 很可能只是调用ToString方法 - 因此与示例2完全相同。

First thing to note is that every class derives from object. 首先要注意的是每个类都来自于对象。

Casting int to object is using an Int32. 将int转换为object正在使用Int32。

Casting string to object is using a String. 将字符串转换为对象正在使用String。

There is no implicit cast from an integer to a string because they are in different parts of the class hierarchy - one does not in any way relate to another. 从整数到字符串没有隐式转换,因为它们位于类层次结构的不同部分 - 一个与任何方式不相关。 However because string is used so often for output object (and therefore all its children) have a ToString() method for convenience. 但是,由于字符串经常用于输出对象(因此,它的所有子对象)都具有ToString()方法,以方便使用。

However Convert is written specifically to be able to convert from one type to another, for example Convert.ToBool(x) can parse "true" or "false" to boolean, and as you have shown it can convert an integer to a string - again this is really a convenience that probably just calls Int32.ToString() under the hood. 但是转换是专门为了能够从一种类型转换为另一种类型而编写的,例如Convert.ToBool(x)可以将“true”或“false”解析为boolean,并且正如您所示,它可以将整数转换为字符串 - 再次,这真的是一个方便,可能只是调用引擎盖下的Int32.ToString()。

Typecasting in C# only works along the lines of class inheritance. C#中的类型转换仅适用于类继承。 Object is the root of all types in C# and therefore all values can be typecast to it. 对象是C#中所有类型的根,因此可以将所有值都强制转换为对象。

string and int do not share the same branch of inheritance and so cannot be directly cast from one to the other. stringint不共享相同的继承分支,因此不能直接从一个继承到另一个继承。

Convert.ToString() is a method designed to convert an integer to a string - there's no typecasting going on, it's just executing a method designed to convert an integer to a string representation. Convert.ToString()是一种旨在将整数转换为字符串的方法-不会进行类型转换,它只是执行一种旨在将整数转换为字符串表示形式的方法。

i.ToString() performs the equivalent functionality to Convert.ToString() , except that i.ToString() has overloads which allow greater flexibility on the representation of the number in string format. i.ToString()执行与Convert.ToString()等效的功能,不同之处在于i.ToString()具有重载,该重载允许以字符串格式表示数字的更大灵活性。

One last note, exceptions to the typecasting rules can be included by the developer by using a public static explicit operator method which permits the developer to convert one value to another as they see fit. 最后一点,开发人员可以使用public static explicit operator方法来包含类型转换规则的例外情况,该方法允许开发人员视情况将一个值转换为另一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM