匿名对象和object的转换
参考http://www.2cto.com/kf/201207/139227.html
下面是一种转换方式:
[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;
}
}
/获取所有员工和账号列表对应关系。
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;
}
}
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET