The Dynamic Type - The Complete C# Tutorial

C# Tutorial TOC Table of Contents

Download PDF + Code samples

PDF Download this entire tutorial as PDF, plus all the code samples, right now!

Chapter/article TOC

  1. Introduction
  2. Booleans
  3. Integers
  4. Floating points
  5. The Char type
  6. Strings
  7. Working with Dates & Time
  8. Nullable types
  9. Implicitly typed variables (the var keyword)
  10. The dynamic Type
    • A dynamic object
    • Changing type
    • Summary
  11. The ExpandoObject
  12. Anonymous Types

Getting started

  • Introduction
  • Visual Studio Community
  • Hello, world!
  • Hello world explained

The Basics

  • Variables
  • Data types
  • Code Comments

Control Structures

  • The if statement
  • The switch statement
  • Loops

Classes

  • Introduction to C# classes
  • Fields
  • Properties
  • Methods (functions)
  • Method parameters
  • Constructors and destructors
  • Method overloading
  • Visibility
  • Static members
  • Inheritance
  • Abstract classes
  • More abstract classes
  • Interfaces
  • Namespaces
  • Constants (the const keyword)
  • Partial Classes
  • Local functions

Collections

  • Arrays
  • Lists
  • Dictionaries

Data types

  • Introduction
  • Booleans
  • Integers
  • Floating points
  • The Char type
  • Strings
  • Working with Dates & Time
  • Nullable types
  • Implicitly typed variables (the var keyword)
  • The dynamic Type
  • The ExpandoObject
  • Anonymous Types

Operators

  • Introduction
  • Comparison operators
  • Increment/decrement operators
  • Addition assignment operators
  • The NULL coalescing operator
  • The String Interpolation Operator

LINQ

  • Introduction
  • LINQ: Query Syntax vs. Method syntax
  • Filtering data: the Where() method
  • Sorting data: the OrderBy() & ThenBy() methods
  • Limiting data: the Take() & Skip() methods
  • Data transformations: the Select() method
  • Grouping data: the GroupBy() Method

Working with Culture & Regions

  • Introduction
  • Application Culture & UICulture
  • The CultureInfo class
  • The RegionInfo class

Regular Expressions (Regex)

  • Introduction
  • Searching with the Regex Class
  • Search/Replace with the Regex Class
  • Regex Modifiers

Misc

  • Randomness with the Random class
  • Starting applications with the Process class

Debugging

  • Introduction to debugging
  • Breakpoints
  • Stepping through the code
  • The tool windows
  • Advanced breakpoints

Advanced topics

  • Enumerations
  • Exception handling
  • Structs

XML

  • Introduction to XML with C#
  • Reading XML with the XmlReader class
  • Reading XML with the XmlDocument class
  • Working with the XmlNode class
  • Using XPath with the XmlDocument class
  • Writing XML with the XmlWriter class
  • Writing XML with the XmlDocument class

C# 3.0

  • Introduction to C# 3.0
  • Automatic properties
  • Object Initializers
  • Collection Initializers
  • Extension Methods

File handling

  • Reading and writing files
  • Manipulating files and directories
  • File and directory information

Data Streams

  • Introduction
  • MemoryStream

Reflection

  • Reflection introduction
  • The right Type
  • Instantiating a class
  • A Reflection based settings class
  • C#
  • ASP.NET MVC
  • ASP.NET WebForms
  • CSS3
  • HTML5
  • JavaScript
  • jQuery
  • PHP5
  • WPF

This article is currently in the process of being translated into Vietnamese (~87% done).

If you are fluent in Vietnamese, then please help us - just point to any untranslated element (highlighted with a yellow left border - remember that images should have their titles translated as well!) inside the article and click the translation button to get started. Or have a look at the current translation status for the Vietnamese language.

If you see a translation that you think looks wrong, then please consult the original article to make sure and then use the vote button to let us know about it.

Metadata

Please help us by translating the following metadata for the article/chapter, if they are not already translated.

If you are not satisfied with the translation of a specific metadata item, you may vote it down - when it reaches a certain negative threshold, it will be removed. Please only submit an altered translation of a metadata item if you have good reasons to do so!

Please login to translate metadata! Already logged in? Please try reloading the page!
  • More info...
  • Looking for the original article in English?
Data types: The dynamic Type

Trong C# phiên bản 4.0, Microsoft đã giới thiệu một kiểu dữ liệu mới: kiểu dữ liệu động. Đó thực chất là tĩnh nhưng không giống các kiểu tĩnh khác, thành viên của đối tượng động không được kiểm tra bởi trình biên dịch. Nó sẽ cho bạn một số ưu điểm của ngôn ngữ động/ép kiểu yếu, trong khi vẫn giữ ưu điểm của ngôn ngữ ép kiểu trong tất cả các trường hợp.

Khai báo kiểu dữ liệu động giống như khai báo các kiểu khác- chỉ dùng từ khóa dynamic thay vì kiểu dữ liệu:

dynamic d1;dynamic d2 = "A string";dynamic d3 = 42;

Bạn có ba loại đối tượng khác nhau - đối tượng đầu tiên là null, đối tượng thứ hai là chuỗi và đối tượng thứ ba là số nguyên. Trình thông dịch sẽ tự động quyết định nó lúc chạy, dựa trên những gì bạn gán cho biến. Nó cũng có nghĩa là trình biên dịch sẽ không kiểm tra những gì bạn làm với những biến này, như minh họa sau:

dynamic d1;dynamic d2 = "A string";dynamic d3 = 42;Console.WriteLine(d2.Length);Console.WriteLine(d3.Length);

String có thuộc tính length, để biết được độ dài của chuỗi là bao nhiêu nhưng số nguyên không có. Trong trường hợp này, tôi thử dùng thuộc tính này ở cả hai biến và trình biên dịch không thông báo gì - nếu những biến này được khai báo như là chuỗi và số nguyên, trình biên dịch sẽ chặn lại. Nhưng vì kiểu chúng ta khai báo là dynamic thì trình biên dịch sẽ biên dịch và chạy. Tuy nhiên, ngay khi trình thông dịch tới dòng cuối cùng thì một ngoại lệ sẽ có, vì rõ ràng bạn không thể truy cập vào thuộc tính không tồn tại này.

Ví dụ này cũng cho chúng ta thấy sự nguy hiểm của kiểu động - bạn phải chú ý rằng những gì bạn làm và đảm baor bạn gọi mọi thuộc tính và phương thức đều đúng vì trình biên dịch không kiểm tra cho bạn,.

A dynamic object

Từ khóa dynamic có thể tất nhiên là được dùng cho kiểu phức tạp hơn số nguyên và chuỗi. Ví dụ có thể dùng cho đối tượng nặc danh như sau:

dynamic user = new{ Name = "John Doe", Age = 42};Console.WriteLine(user.Name + " is " + user.Age + " years old");

Nó cho phép bạn tạo một đối tượng mà không cần định nghĩa lớp. Từ khóa dynamic có thể được dùng nhưng từ khóa var cũng vậy, cũng có thể dùng trong nhiều trường hợp.

You might think that since the type is dynamic, you can just add properties to it later on, like this:

dynamic user = new{ Name = "John Doe", Age = 42};user.HomeTown = "New York";

Since no compile-time checking is done on a dynamic type, this code actually runs, because the compiler doesn't actually validate the existence of the HomeTown property, but as soon as the last line is reached, an exception will be thrown. While a dynamic type IS very dynamic, it doesn't allow you to dynamically add new properties to it. For that, you can use an ExpandoObject, which we'll discuss in the next article.

Changing type

Một biến được khai báo là dynamic không phải là không thuộc kiểu dữ liệu nào. Thay vì vậy, C# sẽ đối xử như bất kỳ kiểu đối tượng nào mà bạn gán cho nó. Trong ví dụ đầu tiên của chúng ta, bạn sẽ thấy các mà chúng ta có thể khai báo một biến là dynamic, gán cả chuỗi hay số nguyên cho nó và sau đó bắt đầu dùng thuộc tính tùy thuộc vào những kiểu dữ liệu này. Tuy nhiên, bạn có thể dễ dàng thay đổi kiểu của biến dynamic – chỉ cần gán giá trị mới cho nó. Đây là ví dụ :

dynamic user = new{ Name = "John Doe", Age = 42};Console.WriteLine(user.GetType() + ": " + user.Name + " is " + user.Age + " years old");user = "Jane Doe";Console.WriteLine(user.GetType() + ": String.Length = " + user.Length);

Chú ý cách chúng ta dùng biến user động : Đầu tiên nó chứa đối tượng nặc danh và sau đó chúng ta gán một chuỗi đơn giản cho nó. Chúng ta kiểm tra kiểu bằng cách dùng phương thức GetType() tìm thấy trong toàn bộ đối tượng của C#, và trong cả hai trường hợp chúng ta truy cập vào thuộc tính trong kiểu chúng ta đó (đầu tiên là Name/Age của đối tượng nặc danh và sau đó là thuộc tính Length trong đối tượng string).

Summary

Từ khóa dynamic cho phép bạn dùng biến không có kiểu dữ liệu cố định – thay vì đó, chúng là kiểu mà chúng lưu biến. Bạn có thể dễ dàng gán một giá trị cho biến động ; và nếu kiểu dữ liệu bạn gán không giống nhau thì biến dynamic cũng sẽ thay đổi theo.

Biến động không được kiểm tra bởi trình biên dịch, cho phép bạn truy cập vào thuộc tính có hay không có. Nó rất linh động nhưng cũng làm cho ứng dụng của bạn dễ bị lỗi. Vì lí do này, bạn có thể muốn giới hạn cách dùng của từ khóa dynamic trong tình huống mà bạn không thể không dùng nó. Ví dụ khi tương tác với kiểu dữ liệu dạng JSON hay XML .

Implicitly typed variables (the var keyword) Previous The ExpandoObject Next This article has been fully translated into the following languages:
  • Chinese
  • Czech
  • Dutch
  • German
  • Italian
  • Portuguese
  • Russian
  • Spanish
Is your preferred language not on the list? Click here to help us translate this article into your language!

Từ khóa » Dynamic Là Gì C#