>  기사  >  백엔드 개발  >  C# 학습일기 16---암시적 변환의 구체적인 사용 사례

C# 학습일기 16---암시적 변환의 구체적인 사용 사례

黄舟
黄舟원래의
2017-01-21 15:02:091641검색

C#의 기본 데이터 유형에 대한 이전 연구에 이어 유형 간의 상호 변환에 대해 알아보겠습니다. C#의 유형 변환은 암시적 변환과 명시적 변환의 두 가지 범주로 나눌 수 있습니다.

암시적 변환:

암시적 변환은 시스템의 기본 변환으로 선언 없이 변환할 수 있습니다. 암시적 변환 프로세스 중에 컴파일러는 변환을 확인하지 않고 안전하게 변환을 수행할 수 있습니다. 예를 들어 int 유형에서 long 유형으로 변환하는 것은 암시적 변환입니다. 암시적 변환은 일반적으로 실패하지 않으며 변환 프로세스 중에 정보가 손실되지 않습니다.

예: int i = 100;

long a = i; 선언 Long 유형으로 변환

암시적 변환은 두 유형 모두에 적용되지 않습니다. 예를 들어 위의 long 유형을 int 유형으로 암시적으로 변환하면 성공하지 못합니다.

long a = 100,

암시적 열거 변환

  • 암시적 참조 변환

  • 암시적 숫자 변환:

  • 암시적 숫자 변환에는 다음 유형이 포함됩니다.

  • sbyte 유형에서 short, int, long, float, double,decimal 유형으로;

ushort 유형에서 int, uint, long, ulong, floot, double, 10진수 유형으로; 🎜>int 유형에서 long, floot, double,decimal 유형으로

  • uint 유형에서 long, ulong, floot, double, 소수 유형으로

  • long형에서 float, double,decimal형으로

  • ulong형에서 float, double,decimal형으로

  • char 유형에서 ushort, int, uint, long, ulong, floot, double,decimal 유형으로

  • float 유형에서 double 유형으로; 🎜> 이렇게 쓰고 정리하자면, 간단히 말하면 저정밀도 타입에서 고정밀도 타입으로의 변환인데(정밀도와 데이터 정보가 손실되지 않기 때문입니다), 고정밀도 타입에서 저정밀도 타입으로의 암묵적인 변환은 없습니다. -정밀도 유형(일부 정보가 손실될 수 있으며 안전하지 않을 수 있음). 유형의 정밀도와 범위는 C# 학습일지 04를 참조하세요. 여기서 기억해야 할 점은 다른 유형에서 Char 유형으로의 암시적 변환이 없다는 것입니다.

  • 암시적 숫자 변환 예:

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace Test  
    {    
        class Program  
        {  
            static void Main(string[] args)  
            {  
                byte x = 255;      //byte 表示的范围0~255  
                short y = x;      //将从byte到short隐式转换  
                y++;  
                Console.WriteLine("y = {0}",y);  
      
                y = 32767; //shot的范围 -32768~32767  
      
                int i = y + 5;  //从 short 到 int 隐式转换扩大范围 结果是准确的  
                y+=5;          //超出范围了结果会不准确  
                Console.WriteLine("y = {0}",y); //y超出范围数据会丢失部分  
                  
                Console.WriteLine("i = {0}",i);   
      
                  
            }  
        }  
    }
  • 결과:
  • 이 예에서 볼 수 있듯이 time 유형 변환의 사용은 여전히 ​​매우 중요합니다.

  • 암시적 열거 변환:

    암시적 열거 변환을 사용하면 10진수 0을 모든 열거 유형으로 변환할 수 있습니다. 0만 변환할 수 있으며 그러한 암시적 변환은 없습니다. 다른 정수의 경우 다음 예를 참조하세요.
  • using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace Test  
    {    
        class Program  
        {  
            enum weekday  //定义一个枚举类型  
            { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };  
            static void Main(string[] args)  
            {  
                weekday day;  
                day = 0;      //隐式将0转换为枚举类型(只能是0)  
                Console.WriteLine(day);  
                  
            }  
        }  
    }
  • 출력 결과는 다음과 같습니다.

      Sunday

    위 코드에서 day = 0을 입력하면 day = 1이 되어야 합니다. 프로세서에서 오류가 발생합니다.

암시적 참조 변환:

모든 참조 유형에서 객체 유형으로 변환

(Person p = new Person) ())

C# 학습일기 16---암시적 변환의 구체적인 사용 사례

클래스 유형 s에서 클래스 유형 t로 변환. 여기서 s는 t의 파생 클래스입니다.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class person     //定义了一个基类(父类) person  
    {   
    }  
    class person1 : person   // person1 派生于基类person,person1就叫person的一个子类,  
    {   
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            person1 per = new person1();  //将子类person1实例化一个对象per  
            person Per = per;        //将子类隐式转换为父类  
              
              
        }  
    }  
}

s 유형에서 인터페이스 유형 t로, 여기서 클래스 s는 인터페이스 t를 구현합니다. (인터페이스(인터페이스)에 대한 내용은 나중에 작성될 예정이므로 메소드 선언에만 사용하고 메소드 정의에는 사용하지 마십시오.)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    public interface Infa   //定义了一个接口  
    {  
        void Output();  
    }  
    class person : Infa    //定义一个person类继承于接口并实现方法  
    {  
        public void Output()  
        {  
            Console.WriteLine("Welcome");  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            person per = new person();  //实例化  
  
            Infa fa = per;    //从person到interface(接口)隐式转换  
              
        }  
    }  
}

인터페이스 유형 s에서 인터페이스 유형 t로 변환(여기서 t는 s의 상위 인터페이스임)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    public interface Infa   //定义了一个接口  
    {  
        void Output();  //接口只声明方法,具体实现由它的派生类写代码决定  
    }  
    public interface infa1 : Infa    //定义一个infa1接口继承于Infa接口  
    {  
        void input();  
    }  
    class person1 : infa1  //由infa1派生一个person1类,因为接口不能直接实例化  
    {   
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            person1 per = new person1 { };  //接口不能直接实例化,需要实例化一个派生于infa1接口person1类  
  
            Infa fa = per;    //实现子接口到父借口隐式转换  
              
        }  
    }  
}

참조 유형 배열 s에서 참조 유형 배열 t로 변환(여기서 s는 t의 파생 클래스이고 배열 차원은 다음과 같아야 함)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class Person //定义一个基类 Person   
    {   
    }  
    class person1 : Person  //由基类派生一个子类person1  
    {   
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            person1[] per = new person1[5];  //实例化一个person1  
  
           Person[] Per = per;    //实现隐式转换  
              
        }  
    }  
}

참조 유형 배열이 값 유형 배열인 경우 다음 코드는 오류를 보고한다는 점을 기억해야 합니다.

class Program  
    {  
        static void Main(string[] args)  
        {  
            int[] n_int = new int[10];  
            double[] n_doubel = new double[10];  
            n_doubel = n_int;  //这里报错啦  
              
        }  
    }

배열 유형에서 System.Array로 변환; (배열은 모든 배열 클래스 참조 이전 기사 ^_^)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            int[] n_int = new int[10];    //实例化一个int类型的数组 n_int  
            Array arr = n_int;  // Array表示的就是数组 所以不能Array[] arr  
        }  
    }

모든 대표 유형에서 System.Delegate로 변환(대리자는 나중에 작성됩니다)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class Program  
    {  
        public static int output(int s)  //定义一个方法  
        {  
            Console.WriteLine("welcome,{0}",s);  
            return 1;  
        }  
  
        public delegate int mydel(int s);  //声明一个委托(以后我会说到委托)  
          
        static void Main(string[] args)  
        {  
            mydel my = new mydel(output);   //将 output方法委托给my  
            Delegate MYDEL = my;    //向 MYDEL 隐式转换  
        }  
    }  
}

以上就是 C#学习日记16----隐式转换具体用例的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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