2011-04-24 47 views
19

是否有可能創建一個屬性名稱包含破折號字符的對象?你可以有一個屬性名稱包含破折號

我正在創建一個匿名對象,以便我可以使用Json.Net將它序列化爲Json,並且我需要的其中一個屬性包含' - '短劃線字符。

的我想要的一個例子是:

var document = { 
    condtions = new { 
     acl = "public-read", 
     bucket = "s3-bucketname", 
     starts-with = "test/path" 
    } 
}; 

我知道當創建對象,然後在序列化的字符串替換它們之後,我可以代替用下劃線的衝刺,而是想知道是否有如果沒有此解決方法,請在語言中進行此操作。

回答

25

你不能用匿名對象來做到這一點;字段名稱必須是有效的標識符。你也可以使用一個字典,其中Json.Net應該很容易連載作爲一個匿名對象:

var document = new { 
    conditions = new Dictionary<string, string>() { 
     { "acl", "public-read" }, 
     { "bucket", "s3-bucketname" }, 
     { "starts-with", "test/path" } 
    } 
}; 
21

不在c#,no。然而,大多數序列化器允許您定製這個 - 通常通過屬性。 IIRC與JSON.NET你想要[JsonProperty("starts-with")]指定名稱。但是你不能在匿名類型上使用屬性,所以你可能需要用你想要的屬性(和屬性)來定義一個類。

+0

我喜歡這種方法來處理非c#兼容名稱 – Turowicz 2015-05-28 16:39:26

+1

這不適用於匿名對象。 – Thomas 2015-07-03 08:40:53

8

不幸的是,這是不可能的,因爲語言不能夠區分以下兩種表現形式:

condition.starts-with; // Read "starts-with" property. 
condition.starts - with; // Read "starts" property and subtract "with" variable. 
相關問題