2016-12-21 86 views
1

如何設置/獲取動態對象的屬性'object'?名爲'object'的動態訪問屬性

dynamic json = new ExpandoObject(); 

json.foo = "bar"; // OK 
json.object = "content"; // Does not compile 
json["object"] = "content"; // throw RuntimeBinderException 
((IDictionary<string, object>)json)["object"] = "content"; // OK, but ... 

我想訪問一個REST api,那需要我設置一個名爲'object'的屬性。最後的解決方案實際上解決了這個問題,但我覺得我錯過了一些東西。

回答

2

object是C#關鍵字。
爲了定義object屬性,你可以告訴編譯器,在這種情況下,「對象」是一個屬性的名稱,而不是使用關鍵字「@」:

[email protected] = "content"; 

它適用於所有關鍵字:[email protected][email protected][email protected]

但是,強烈建議儘量減少它的使用,因爲它會惡化可讀性。如果你想在你的輸出JSON的object屬性,你可以定義一個類序列化和使用JsonPropertyAttribute告訴序列化序列化作爲object

public class SomeClass 
{ 
    [JsonProperty("object")] 
    public string ObjectContent { get;set; } 
} 

這將導致到

{ 
    "object": "content" 
}