c#匿名型別

來源:互聯網
上載者:User

標籤:

匿名型別常見於指令碼語言如js,as等等。

一  使用對象序列化為匿名對象

匿名型別的好處在於臨時使用一次資料不需要,先定義再使用,比較方便,如在js中定義一個對象

var obj={id=‘001‘,name=‘xxx‘};

使用則直接使用obj.id=‘0025‘;

但是在c#這種強型別的語言中並不是這樣方便,比如我需要將一個js介面返回的json資料進行還原序列化,在此處以百度地圖定位介面為例:

http://api.map.baidu.com/location/ip
返回參數:
{          address: "CN|北京|北京|None|CHINANET|1|None",   #地址          content:       #詳細內容          { address: "北京市", #簡要地址 address_detail: #詳細地址資訊 { city: "北京市", #城市 city_code: 131, #百度城市代碼 district: "", #區縣 province: "北京市", #省份 street: "", #街道 street_number: "" #門址 }, point: #百度經緯度座標值 { x: "116.39564504", y: "39.92998578" } }, status: 0 #返回狀態代碼 }

如果實在js中則直接使用var location=JSON.parse(str); 屬性直接可以使用location.xx使用
如果在c#中先得定義一個資料類,然後還原序列化為該資料類,在net4過後增加了匿名型別來勉強應付一下,不過有總比沒有好,下面來看怎樣使用

1 基本思路
將字串還原序列化為一個Jobject對象
2 使用屬性


第一種做法(匿名類):

var anonymous = new { a = 0, b = String.Empty, c = new int[0], d = new Dictionary<string, int>() };
var o2 = JsonConvert.DeserializeAnonymousType(json, anonymous);

Console.WriteLine(o2.b);
Console.WriteLine(o2.c[1]);第二種做法(匿名類):

 

var o3 = JsonConvert.DeserializeAnonymousType(json, new { c = new int[0], d = new Dictionary<string, int>() });
Console.WriteLine(o3.d["y"]);
第三種做法(索引器):
 

 

     實際上,我們也可以直接還原序列化為 JObject,然後通過索引器直接存取。JObject、JProperty 等都繼承自 JToken,它重載了基元類型轉換操作符,我們可以直接得到實際結果。

var o2 = JsonConvert.DeserializeObject(json) as JObject;

Console.WriteLine((int)o2["a"]);
Console.WriteLine((string)o2["b"]);
Console.WriteLine(o2["c"].Values().Count());
Console.WriteLine((int)o2["d"]["y"]);

二 自訂構建匿名對象
2.1 指明屬性
var obj=new {
  屬性a="",
  屬性b=3432
};

2.2 不指明屬性
var pt=new Point(122,30);

var obj=new {pt.x,pt.y }
此時x,y則預設為該obj對象屬性





c#匿名型別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.