>  기사  >  백엔드 개발  >  C# 학습 일기 17---유형 변환의 구체적인 사용 사례 보기

C# 학습 일기 17---유형 변환의 구체적인 사용 사례 보기

黄舟
黄舟원래의
2017-01-21 15:07:061549검색

C#의 유형 변환에는 이전 글에서 소개한 암시적 유형 변환 외에도 선언해야 하는 유형 변환------명시적 유형 변환이 있습니다.

Explicit 유형 변환(강제 유형 변환이라고도 함)은 변환을 수행할 때 변환 유형을 명시적으로 지정해야 합니다. 예를 들어, long 유형을 int 유형으로 변환하는 경우 이 변환은 정밀도를 잃는 변환이므로 시스템은 이를 수행하지 않습니다. 자동으로 암시적 변환을 수행하므로 강제 변환이 필요합니다:

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

다음과 같은 두 가지 유형에 대해서는 표시 유형 변환이 적용되지 않습니다.

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

따라서 표시 유형 변환에도 특정 사항이 있습니다. 규칙:

  • 숫자 변환 표시

  • 열거 변환 표시

  • 참조 변환 표시;

디스플레이 변환이 항상 성공하는 것은 아니며, 종종 정보의 손실이 발생할 수 있습니다(종류가 다르기 때문에 범위와 정밀도도 다릅니다. 자세한 내용은 데이터를 참조하세요) 유형) 표시 변환에는 모든 암시적 변환이 포함됩니다. 따라서 암시적 변환은 다음과 같이 명시적 변환 형식으로 작성할 수도 있습니다.

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

표시 숫자 변환:

표시 숫자 변환을 참조합니다. 다음과 같이 값 유형과 값 유형 간의 변환 규칙:

  • sbyte에서 byte, ushort, uint, ulong, char 유형

  • 바이트에서 sbyte, char 유형;

  • short에서 sbyte, byte, ushort, uint, ulong, char 유형

  • 에서 ushort에서 sbyte, byte, short, char 유형으로 ;

  • int에서 sbyte로, byte, short, ushort, uint, ulong, char 유형

  • uint에서 sbyte, byte, short, ushort, int, char 유형

  • long에서 sbyte, byte, short, ushort, int, uint, ulong, char 유형으로; ;

  • ulong에서 sbyte, byte, short, ushort, int, uint, long, char 유형

  • char에서 sbyte로, byte, short 유형

  • float에서 sbyte, byte, short, ushort, int, uint, long, ulong, char,decimal 유형으로;

    double에서 sbyte, byte, short, ushort, int, uint, long, ulong, float, char, 십진수 유형
  • 십진수에서 sbyte, byte, short, ushort, int, uint, long, ulong, float, char, double type;
  • 이렇게 많이 작성한 후에 요약하자면 고정밀도에서 저정밀도로의 변환일 수도 있습니다. 보존 변환 또는 반올림 변환으로 작성해 보겠습니다. 예:
  • 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);  
                  
            }  
        }  
    }
실행 결과:


double 데이터 범위가 float의 유효한 값 범위를 초과하면 표시됩니다. 변환 시 9번째 자리는 반올림되고, int형으로 변환 시 정수 부분만 남게 됩니다. C# 학습 일기 17---유형 변환의 구체적인 사용 사례 보기

표시 열거형 변환:

표시 열거형 변환에는 다음 내용이 포함됩니다.

From sbyte, byte, short, ushort , int, uint, long, ulong, float, char, double,decimal 유형을 모든 열거 유형으로
  • 모든 열거 유형에서 sbyte, byte, short, ushort, int, uint로 변환 , long, ulong, float, char, double, 10진수 유형
  • 모든 열거형에서 다른 열거형으로
  • 작성합니다. 예:
  • 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);  
                  
            }  
        }  
    }
실행 결과:

참조 변환 표시: C# 학습 일기 17---유형 변환의 구체적인 사용 사례 보기

객체에서 임의의 참조 유형으로 변환

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类  
              
        }  
    }  
}

클래스 유형 s에서 클래스 유형 t로 변환(여기서 s는 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;  //将父类转换为子类  
              
        }  
    }  
}

클래스 유형 s에서 인터페이스 t로 변환, 여기서 s는 밀봉되지 않음). 인터페이스에 대해서는 나중에 쓰겠습니다. 메서드 선언만 하고 메서드를 정의하지는 않습니다.)

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;  // 显示转换
                        
        }
    }
}

인터페이스 유형 s에서 클래스 유형 t로 변환. 여기서 t는 봉인된 클래스가 아니며 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;  // 显示转换  
                          
        }  
    }  
}

인터페이스 유형에서 변환 s를 인터페이스 유형 t로, 여기서 s는 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;  // 显示转换  
                          
        }  
    }  
}

참조 유형 배열 및 참조 유형 배열 표시 변환, 여기서 둘은 상위 클래스 및 하위 클래스입니다. 관계(차원은 다음과 같아야 함) 동일)

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;      //显示转换   
              
        }  
    }  
}

다음 배열로 변경하면 작동하지 않습니다

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;     //这里出错啦  
              
        }  
    }  
}

System.Array에서 배열 유형으로(array는 모든 배열 유형의 기본 클래스입니다)

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;    //显示转换  
        }  
    }  
}

System.Delegate에서 대표(delegate)형으로

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;  //显示转换  
        }  
    }  
}

위는 C# 학습일지 17의 내용입니다---형 변환의 구체적인 사용 사례를 표시하고 있으니, 더 많은 관련 내용을 참고해주세요. PHP 중국어 홈페이지(www.php.cn)로!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.