匿名对象和object的转换

参考http://www.2cto.com/kf/201207/139227.html

有时候经常用到需要把一个匿名对象存入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;
        }

}

posted @ 2013-07-31 12:59  跟着阿笨一起玩.NET  阅读(409)  评论(0编辑  收藏  举报