亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將匿名類型轉換為字典

將匿名類型轉換為字典

C#
Smart貓小萌 2023-12-17 20:02:15
我正在嘗試創建一個將匿名類型轉換為字典的函數。 我正在查看此鏈接線程中已接受的答案。但是我收到錯誤無法使用 lambda 表達式作為動態參數 分派操作而不首先將其強制轉換為委托或 表達式樹類型這就是我想做的public Dictionary<string,string> convert(dynamic dtype){ var props = content.GetType().GetProperties(); var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();  // <----Exception var result = string.Join("&", pairs); return result} 關于如何解決這個問題有什么建議嗎?我正在嘗試這樣做       var student= new        {            // TODO: Make this figure out and return underlying device status.            type = "Active",        }; var dict = convert(student);
查看完整描述

1 回答

?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

例外在這里:


 x.GetValue(a, null)

只需將 a 更改為 content,如下所示:


var pairs = props.Select(x => x.Name + "=" + x.GetValue(content, null)).ToArray();

content 是您的匿名對象的名稱。


但是你寫的這個解決方案不返回字典。 如果您想要字典,請執行以下操作:


public static Dictionary<string, string> convert(object content)

        {


            var props = content.GetType().GetProperties();

            var pairDictionary = props.ToDictionary(x => x.Name,x=>x.GetValue(content,null)?.ToString());

            return pairDictionary;

        }


查看完整回答
反對 回復 2023-12-17
  • 1 回答
  • 0 關注
  • 197 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號