Casting (C# Programming Guide)

來源:互聯網
上載者:User
Casting (C# Programming Guide) Visual Studio 2005 {
ChangeVersionClick()
}">Other Versions
  • Visual Studio 2010
  • Visual Studio 2008

 

Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed. For example:

VB C#C++F#JScriptCopy
static void TestCasting(){    int i = 10;    float f = 0;    f = i;  // An implicit conversion, no data will be lost.    f = 0.5F;    i = (int)f;  // An explicit conversion. Information will be lost.}

A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined. You can write custom conversion operators to convert between user-defined types. For more information about defining a conversion operator, see explicit (C# Reference) and implicit (C# Reference).

{
CA_Click('f5241fcb-4792-4ca3-994c-9934cefbf8e9','Expand','Collapse')
}" href="javascript:void(0)"> Example

The following program casts a double to an int. The program will not compile without the cast.

VB C#C++F#JScriptCopy
class Test{    static void Main()    {        double x = 1234.7;        int a;        a = (int)x;  // cast double to int        System.Console.WriteLine(a);    }}
{
CA_Click('8b750198-2730-490c-b335-b8fda1c4d336','Expand','Collapse')
}" href="javascript:void(0)"> Output

1234

{
CA_Click('8e9dbb62-7df4-426b-9004-472c6bba1ba7','Expand','Collapse')
}" href="javascript:void(0)"> C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 7.6.6 Cast Expressions

  • 6.1 Implicit Conversions

  • 6.2 Explicit Conversions

{
CA_Click('d2bbdc5a-154f-46dc-8d91-6e3dc7ed64a0','Expand','Collapse')
}" href="javascript:void(0)"> See Also

Reference

Data Types (C# Programming Guide)
() Operator (C# Reference)
explicit (C# Reference)
implicit (C# Reference)
Concepts

C# Programming Guide
Conversion Operators (C# Programming Guide)
Generalized Type Conversion
Explicit Conversion
Exported Type Conversion

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.