Chuyển đổi kiểu dữ liệu trong C#

Chuyển đổi kiểu dữ liệu trong C# là biến đổi một kiểu dữ liệu này thành kiểu dữ liệu khác. Nó còn được gọi là ép kiểu. Trong C#, ép kiểu có hai mẫu sau:

  • Chuyển đổi kiểu ngầm định (implicit) – Việc chuyển đổi này được thực hiện bởi C# theo một phương thức an toàn kiểu (type-safe). Ví dụ: việc chuyển đổi từ các lớp kế thừa thành các lớp cơ sở.
  • Chuyển đổi kiểu tường minh (explicit) – Việc chuyển đổi này được thực hiện một cách rõ ràng bởi người dùng bằng việc sử dụng các hàm được định nghĩa trước. Các chuyển đổi kiểu tường minh cần một toán tử cast.

Ví dụ sau minh họa một sự chuyển đổi kiểu tường minh trong C#:

namespace TypeConversionApplication 
{
   public class ExplicitConversion 
   {
      public static void Main(string[] args) 
	  {
         double d = 5673.74; 
         int i;
         
         // cast double to int.
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadLine();
      }
   }
}
C#

Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:

5673

Bạn có thể tự biên dịch và xem kết quả online tại đây.

Phương thức Chuyển đổi kiểu dữ liệu trong C#

C# cung cấp các phương thức chuyển đổi kiểu có sẵn được liệt kê trong bảng sau:

STT Phương thức & Miêu tả
1 ToBooleanChuyển đổi một kiểu thành một giá trị Boolean, nếu có thể
2 ToByteChuyển đổi một kiểu thành một byte
3 ToCharChuyển đổi một kiểu thành một Unicode character, nếu có thể
4 ToDateTimeChuyển đổi một kiểu (kiểu integer hoặc string) thành các cấu trúc date-time
5 ToDecimalChuyển đổi một kiểu số thực hoặc số nguyên thành một kiểu thập phân
6 ToDoubleChuyển đổi một kiểu thành một kiểu double
7 ToInt16Chuyển đổi một kiểu thành một 16-bit integer
8 ToInt32Chuyển đổi một kiểu thành một 32-bit integer
9 ToInt64Chuyển đổi một kiểu thành một 64-bit integer
10 ToSbyteChuyển đổi một kiểu thành một kiểu signed byte
11 ToSingleChuyển đổi một kiểu thành một số small floating point
12 ToStringChuyển đổi một kiểu thành một string
13 ToTypeChuyển đổi một kiểu thành một kiểu đã xác định
14 ToUInt16Chuyển đổi một kiểu thành một kiểu unsigned int
15 ToUInt32Chuyển đổi một kiểu thành một kiểu unsigned long
16 ToUInt64Chuyển đổi một kiểu thành một unsigned big integer

Ví dụ sau minh họa cách chuyển đổi các kiểu dữ liệu đa dạng thành kiểu dữ liệu string trong C#:

using System;

namespace TypeConversionApplication 
{
   public class StringConversion 
   {
      public static void Main(string[] args) 
      {
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(f.ToString());
         Console.WriteLine(d.ToString());
         Console.WriteLine(b.ToString());
         Console.ReadLine();
            
      }
   }
}
C#

Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:

75
53.005
2345.7652
True

Bạn có thể tự biên dịch và xem kết quả online tại đây.

Boxing và Unboxing trong C#

Mọi kiểu dữ liệu trong C#, từ kiểu có sẵn hay do người dùng tự định nghĩa, đều được kế thừa từ lớp cơ bản là System.Object.

Boxing là quá trình chuyển đổi một kiểu giá trị thành kiểu object. Nếu bạn chưa biết kiểu giá trị là gì thì vui lòng xem lại bài Kiểu dữ liệu trong C#.

Còn unboxing là quá trình ngược lại với boxing đó là chuyển từ kiểu object sang kiểu giá trị.

int i = 123;
// boxing
object o = i;
// unboxing
i = (int)o;
C#

Boxing

Boxing là một chuyển đổi ngầm định (implicit) của một kiểu giá trị thành kiểu object. Quá trình boxing một kiểu giá trị sẽ tạo một thể hiện đối tượng trên bộ nhớ heap và sao chép giá trị vào đối tượng mới này.

int i = 123;
// Boxing copies the value of i into object o.
object o = i;
C#

Kết quả của câu lệnh này là tạo ra một tham chiếu đối tượng o trên stack, tham chiếu một giá trị của kiểu int, trên heap. Giá trị này là bản sao của giá trị kiểu giá trị được gán cho biến i. Sự khác biệt giữa hai biến i và o, được minh họa trong hình ảnh sau đây:

Unboxing

Unboxing là một chuyển đổi tường minh (explicit) từ kiểu object sang kiểu giá trị. Unboxing gồm 2 bước:

  • Kiểm tra thể hiện đối tượng để đảm bảo rằng giá trị được boxing có thể chuyển sang kiểu giá trị.
  • Sao chép giá trị từ thể hiện đối tượng vào biến kiểu giá trị.

Ví dụ dưới đây thể hiện quá trình boxing và unboxing:

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing
C#

Quá trình unboxing được minh họa như hình sau:

Để quá trình unbox thành công lúc thực thi thì mục được unboxing phải là một tham chiếu tới một đối tượng được tạo ra trước đó bởi quá trình boxing một thể hiện của kiểu giá trị đó.

Cố gắng unboxing null sẽ gây ra ngoại lệ NullReferenceException. Việc cố gắng unboxing một kiểu giá trị không tương thích sẽ gây ra ngoại lệ UnlimitedCastException.

Ví dụ sau đây cho thấy một trường hợp unboxing không hợp lệ và kết quả gây ra ngoại lệ UnlimitedCastException. Sử dụng try và catch, một thông báo lỗi được hiển thị khi xảy ra lỗi.

public class TestUnboxing
{
    public static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        try
        {
            int j = (short)o;  // attempt to unbox

            System.Console.WriteLine("Unboxing OK.");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
        }
    }
}
C#

Chương trình này xuất ra:

Specified cast is not valid. Error: Incorrect unboxing.

Bạn có thể tự biên dịch và xem kết quả online tại đây.

Nếu bạn sửa dòng này:

int j = (short) o;
C#

thành:

int j = (int) o;
C#

Việc chuyển đổi sẽ được thực hiện và bạn sẽ nhận được kết quả đầu ra:

Unboxing OK.

Hiệu năng

Boxing và unboxing là các quá trình tính toán tốn kém. Khi một kiểu giá trị được boxing, một đối tượng mới phải được phân bổ và xây dựng. Ở mức độ thấp hơn, việc chuyển kiểu cần thiết cho việc unboxing cũng tốn kém về mặt tính toán.

Do vậy bạn nên cân nhắc và hạn chế tối đa việc sử dụng boxing và unboxing trong quá trình lập trình.

Bạn có muốn xem bài viết tiếp theo không? Nó ở dưới đây nè.

 

42 thoughts on “Chuyển đổi kiểu dữ liệu trong C#

  1. temp mail says:

    Simply wish to say your article is as amazing. The clearness in your post is just nice and i could assume you’re an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.

  2. Rastrear Celular says:

    Você pode usar o software de gerenciamento dos pais para orientar e supervisionar o comportamento dos filhos na Internet. Com a ajuda dos 10 softwares de gerenciamento de pais mais inteligentes a seguir, você pode rastrear o histórico de chamadas de seu filho, histórico de navegação, acesso a conteúdo perigoso, aplicativos que eles instalam etc.

  3. Registrati says:

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  4. fake email address says:

    I wanted to take a moment to commend you on the outstanding quality of your blog. Your dedication to excellence is evident in every aspect of your writing. Truly impressive!

  5. youtube to mp3 320 says:

    My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks

  6. insightsway says:

    Thank you for the auspicious writeup It in fact was a amusement account it Look advanced to more added agreeable from you By the way how could we communicate

  7. etruesports says:

    I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers

  8. discoverblog says:

    I do believe all the ideas youve presented for your post They are really convincing and will certainly work Nonetheless the posts are too short for novices May just you please lengthen them a little from subsequent time Thanks for the post

  9. kingymab says:

    My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks

  10. Bacará móvel says:

    Alguém essencialmente deu uma mão para fazer artigos significativos. Id state Essa é a primeira vez que visitei a página do seu site e até agora fiquei surpreso com a pesquisa que você fez para tornar este envio real incrível Tarefa maravilhosa

  11. spacedaily says:

    Nem sei como vim parar aqui mas achei ótimo esse post não sei quem você é mas com certeza você está indo para um blogueiro famoso se ainda não o é.

  12. minihints says:

    Meu primo me recomendou este site, não tenho certeza se este post foi escrito por ele, pois ninguém mais sabe tão detalhadamente sobre minha dificuldade. Você é maravilhoso, obrigado

  13. kalorifer soba says:

    Your blog is a constant source of inspiration for me. Your passion for your subject matter shines through in every post, and it’s clear that you genuinely care about making a positive impact on your readers.

  14. kalorifer sobası says:

    Your writing is a true testament to your expertise and dedication to your craft. I’m continually impressed by the depth of your knowledge and the clarity of your explanations. Keep up the phenomenal work!

  15. top888casino says:

    Your blog is a testament to your passion for your subject matter. Your enthusiasm is infectious, and it’s clear that you put your heart and soul into every post. Keep up the fantastic work!

  16. temp mail says:

    I share your level of enthusiasm for the work you’ve produced. The sketch you’ve displayed is refined, and the material you’ve authored is impressive. Nevertheless, you seem anxious about the prospect of heading in a direction that could cause unease. I agree that you’ll be able to address this concern in a timely manner.

  17. temp mail says:

    I was just as enthralled by your work as you were. The visual presentation is refined, and the written content is sophisticated. However, you seem anxious about the possibility of presenting something that could be perceived as questionable. I believe you’ll be able to rectify this matter in a timely manner.

  18. trendaddictor says:

    Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do so Your writing taste has been amazed me Thanks quite nice post

  19. globesimregistration says:

    Your blog is a testament to your dedication to your craft. Your commitment to excellence is evident in every aspect of your writing. Thank you for being such a positive influence in the online community.

  20. Tommy Polczynski says:

    I needed to put you the very small remark so as to give many thanks yet again for all the remarkable thoughts you have contributed above. It’s certainly wonderfully generous of people like you to grant freely what exactly some people would have made available for an electronic book to help make some money on their own, and in particular now that you might have tried it in case you decided. These things also acted to be a good way to be certain that the rest have the same dreams much like my personal own to figure out way more when it comes to this problem. I’m sure there are some more fun times in the future for individuals who look into your site.

  21. globesimregistration says:

    you are in reality a good webmaster The website loading velocity is amazing It sort of feels that youre doing any distinctive trick Also The contents are masterwork you have done a fantastic job in this topic

  22. globesimregistration says:

    Your blog is a breath of fresh air in the often stagnant world of online content. Your thoughtful analysis and insightful commentary never fail to leave a lasting impression. Thank you for sharing your wisdom with us.

Leave a Reply

Your email address will not be published. Required fields are marked *