.
在 C# 4.0 中 新加入的資料型態 dynamic可以大幅度簡化程式內容
讓整體程式看起來更簡潔
dynamic 型別可以是一種在執行時才去連結的型態,它會告訴編譯器
在編譯時(compile time)不去檢查 dynamic 型別所代表的資料型態,把它視為類似object
在執行時(run time) 才會決定,這代表不用在程式中宣告一個固定的型別
由 C# 程式自動在執行期間獲取資料的型別
以下範例為直接宣告dynamic 類別 和 List,並在按下按鈕時動態生成類別資料成員與內容
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Dynamic;
- using System.Threading;
-
- namespace dynamic_test
- {
- public partial class Form1 : Form
- {
- //宣告dynamic class
- private dynamic test_dynamic;
- //宣告dynamic list
- dynamic test_dynamic_list = new List<dynamic>();
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- //實體化dynamic class
- test_dynamic = new ExpandoObject();
- //dynamic class 加入 property 與 content
- test_dynamic.data = textBox1.Text;
- test_dynamic_list.Add(test_dynamic);
- textBox1.Text = "";
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- richTextBox1.Text = "";
- //列出所有加入 dynamic list 的資料
- foreach (dynamic content in test_dynamic_list)
- {
- richTextBox1.Text += content.data + "\n";
- }
- }
-
- }
- }
首先輸入 資料一 並加入
加入資料二
加入資料三
列出所有dynamic List 中的資料