天天看點

匿名對象和object的轉換

匿名對象和object的轉換
匿名對象和object的轉換

有時候經常用到需要把一個匿名對象存入session或List<object>或其他容器中,可是取出來的時候變成object了,不太友善使用。 

下面是一種轉換方式:

[csharp] 

    class Program  

    {  

        static void Main(string[] args)  

        {  

            List<object> olist = new List<object>();  

            olist.Add(new { Name = "Hauk", Age = 22 });  

            olist.Add(new { Name = "Emily", Age = 22 });  

            //使用動态類型  

            foreach (dynamic item in olist)  

            {  

                Console.WriteLine(item.Name);  

            }  

            //做類型轉換  

            var obj = ChangeType(olist[0], new { Name = "", Age = 0 });  

            Console.WriteLine(obj.Name);  

            //直接反射  

            Console.WriteLine(olist[0].GetType().GetProperty("Name").GetValue(olist[0]).ToString());  

        }  

        static T ChangeType<T>(object obj, T t)  

            return (T)obj;  

    }  

View Code

             /擷取所有員工和賬号清單對應關系。

            DataTable dtAccoutIDList = bll.GetList(model);

            //添加一行空行。

            DataRow dr = dtAccoutIDList.NewRow();

            dr["AccountName"] = "";

            dr["AccountID"] = "-2";

            dtAccoutIDList.Rows.InsertAt(dr, 0);

            dtAccoutIDList.AcceptChanges();

            this.cmbAccountList.DisplayMember = "AccountName";

            this.cmbAccountList.ValueMember = "[AccountID]";

   var query3 = dtAccoutIDList.AsEnumerable().Select(s => new { AccountID = s["AccountID"].ToInt(), AccountName = s["AccountName"].ToString() }).OrderBy(o => o.AccountName).Distinct().ToList();

                this.cmbAccountList.DataSource = query3;

--

将資料源轉換為匿名對象數組。

var cmbAccountDataSource = this.cmbAccountList.DataSource.ChangeType(new[] { new { AccountID = 0, AccountName = "" } }.ToList()); 

或者 this.cceAccount.Properties.DataSource = accounts.Select(m => new { Account = m }).ToList();

将選擇的項,轉換為匿名對象

var cmbSelectedItem = this.cmbAccountList.SelectedItem.ChangeType(new { AccountID = 0, AccountName = "" });

int selectedAccountID=cmbSelectedItem.AccountID

string selectedAccoutName=cmbSelectedItem.AccountName

///擴充方法

 public static class Extension

 {

 public static T ChangeType<T>(this object obj, T t)

        {

            return (T)obj;

        }

}