Home Backend Development C#.Net Tutorial C# Learning Diary 17---Show specific use cases of type conversion

C# Learning Diary 17---Show specific use cases of type conversion

Jan 21, 2017 pm 03:07 PM

In the type conversion of C#, in addition to the implicit type conversion introduced in the previous article, there is also a type conversion that needs to be declared by us ----- explicit type conversion.

Display type conversion , also called forced type conversion, it requires us to explicitly specify the conversion type when performing conversion. For example, when we convert the long type to the int type, since this conversion is a conversion that loses precision, the system will not automatically perform implicit conversion. formula conversion, so forced conversion is required:

      long l = 6000;
                  int i = (int)l;    //需要用在 ()里面声明转换类型
Copy after login

Display type conversion is not true for any two types, such as:

       int i = 6000;
                  string i = (string)i;    //这里会报错
Copy after login

Therefore, display type conversion also has certain rules:

  • Display numeric conversion;

  • Display enumeration conversion;

  • Display reference conversion;

Display conversion is not always successful, and may often cause the loss of information (because the types are different, the range and precision are also different. For details, please refer to the data type). Display conversion includes all implicit conversions. Therefore, implicit conversion can also be written in the form of explicit conversion, such as:

        int i = 6000;
                            long l = (long)i;    //等价于 long l = i;
Copy after login

Display numerical conversion:

Display numerical conversion refers to the conversion between value type and value type, as follows Rules:

  • From sbyte to byte, ushort, uint, ulong, char type;

  • From byte to sbyte, char type;

  • From short to sbyte, byte, ushort, uint, ulong, and char types;

  • From ushort to sbyte, byte, short, and char types ;

  • From int to sbyte, byte, short, ushort, uint, ulong, char type;

  • From uint to sbyte, byte, short, ushort, int, char types;

  • From long to sbyte, byte, short, ushort, int, uint, ulong, char types;

  • From ulong to sbyte, byte, short, ushort, int, uint, long, char types;

  • From char to sbyte, byte, short type;

  • From float to sbyte, byte, short, ushort, int, uint, long, ulong, char, decimal type;

  • From double to sbyte, byte, short, ushort, int, uint, long, ulong, float, char, decimal type;

  • from decimal to sbyte, byte, short, ushort, int, uint, long, ulong, Float, char, double types;

After writing so much, let’s summarize it. It is the conversion from high precision to low precision. It may be a retaining conversion or a rounding conversion. Write Example:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        static void Main(string[] args)  
        {  
            double n_double = 1.73456789;  
            float n_float = (float)n_double;  //显示转换 float的有效为只有8位(.也是一位)所以从第9位四舍五入  
  
            int n_int = (int)n_double; //只保留整数  
  
            Console.WriteLine("n_float = {0}\nn_int = {1}",n_float,n_int);  
              
        }  
    }  
}
Copy after login

Running results:


C# Learning Diary 17---Show specific use cases of type conversion

## Comparison found that when the double data range exceeds the valid value range of float, it is displayed The 9th digit is rounded when converting, and only the integer part is retained when converting to int type.

Display enumeration conversion:

Display enumeration conversion includes the following contents:

  • From sbyte, byte, short, ushort, int, uint, long, ulong, float, char, double, decimal types to any enumeration type;

  • From any enumeration type to sbyte, byte, short, ushort, int, uint, long, ulong, float, char, double, decimal types;

  • From any enumeration type to any other enumeration type;

Write an example:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        enum weekday   //定义2个枚举  
        {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday }  
        enum Month  
        {Janurary=1,February,March,April,May,Jun,July }  
        static void Main(string[] args)  
        {  
            int n_int = 2;  
            double n_double = 3.0;  
            decimal n_decimal = 5m;  //声明decimal 类型要加m  
  
            weekday weki = (weekday)n_int;     //从int、double、decimal到枚举转换  
            weekday wekd = (weekday)n_double;  
            weekday wekde = (weekday)n_decimal;  
  
            weekday wek = weekday.Tuesday;   //枚举类型之间的转换  
            Month mon = (Month)wek;  
  
            int i = (int)wek;  //从枚举类型到int的转换  
            int t = (int)mon;  
            Console.WriteLine("n_int = {0}\nn_double = {1}\nn_decimal = {2}",weki,wekd,wekde);  
            Console.WriteLine("wek = {0}\nmon = {1}\nwek ={2}\tmon = {3}",wek,mon,i,t);  
              
        }  
    }  
}
Copy after login

Running result:

C# Learning Diary 17---Show specific use cases of type conversion##Display reference conversion:

From object to any reference type Conversion;

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        //定义2个类 teacher与man  
        class teacher  
        { }  
        class man  
        { }  
        static void Main(string[] args)  
        {  
            man per = new man();  //将man实例化一个对象per  
            object o = per;      //装箱  
            teacher p = (teacher)o;  // 将o显示转换为teacher类  
              
        }  
    }  
}
Copy after login

Conversion from class type s to class type t, where s is the base class of t;

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        class man   //定义一个基类  
        { }  
        class student:man  //student继承man  
        { }  
        static void Main(string[] args)  
        {  
            man per = new man();  //man实例化一个对象per  
            student stu = (student)per;  //将父类转换为子类  
              
        }  
    }  
}
Copy after login

Conversion from class type s to interface t, where s is not sealed Class, does not implement t; (The content of the interface will be written later, it only declares methods but does not define methods)

using System;

using System.Collections.Generic;

using System.Linq;
using System.Text;


namespace Test
{  
    class Program
    {
        public interface teacher  //定义一个接口 
        { }
        class student   //定义一个类
        { }
        static void Main(string[] args)
        {
            student stu = new student(); //实例化一个对象
            teacher tea = (teacher)stu;  // 显示转换
                        
        }
    }
}
Copy after login

Conversion from interface type s to class type t, where t is not a sealed class and does not implement s;

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        public interface man  //定义一个接口   
        { }  
        class teacher:man  //定义一个继承于man的类man  
        { }  
        class student   //定义一个新类  
        { }  
        static void Main(string[] args)  
        {  
            man teac=new teacher(); //间接实例化一个接口  
            student stu = (student)teac;  // 显示转换  
                          
        }  
    }  
}
Copy after login

Conversion from interface type s to interface type t, where s is not a sub-interface of t;

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        public interface man  //定义一个接口   
        { }  
        class teacher : man    //由接口派生一个类  
        { }  
        public interface person //定义一个接口  
        { }  
        class student:person   //由接口派生一个类  
        { }  
        static void Main(string[] args)  
        {  
            man teac=new teacher(); //间接实例化一个接口  
            person stu = (person)teac;  // 显示转换  
                          
        }  
    }  
}
Copy after login

Reference type array and reference type array display conversion, both of which are parent classes and subclasses The relationship (the dimensions must be the same)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        class teacher  
        { }  
        class student:teacher  //studnet继承teacher  
        { }  
        static void Main(string[] args)  
        {  
            teacher[] teac = new teacher[5];  
            student[] stu = new student[5];  
            stu = (student[])teac;      //显示转换   
              
        }  
    }  
}
Copy after login

If you change to the following array, it will not work

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        static void Main(string[] args)  
        {  
           double[] n_double = new double[5];  
            float[] n_float = new float[5];  
            n_float = (float[])n_double;     //这里出错啦  
              
        }  
    }  
}
Copy after login

From System.Array to array type (array is the base class of all array types)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
        static void Main(string[] args)  
        {  
           Array arr = new Array[5];   //定义一个Array类型的数组并初始化  
           double[] d = new double[5];  
           d = (double[])arr;    //显示转换  
        }  
    }  
}
Copy after login

From System.Delegate to representative (delegate) type

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{    
    class Program  
    {  
          
        public static delegate int mydele();  //声明一个委托  
  
        class DE : Delegate  //定义一个继承于Delegate 的类DE  
        { }  
        static void Main(string[] args)  
        {  
            Delegate MY =new DE();   // 将Delegate 抽象类间接实例化  
            mydele my = (mydele)MY;  //显示转换  
        }  
    }  
}
Copy after login

The above is the content of C# Learning Diary 17---Displaying specific use cases of type conversion. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# .NET Security Best Practices: Preventing Common Vulnerabilities C# .NET Security Best Practices: Preventing Common Vulnerabilities Apr 05, 2025 am 12:01 AM

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.

See all articles