【问题标题】:Can you have a property name containing a dash你能有一个包含破折号的属性名称吗
【发布时间】:2011-04-24 15:58:55
【问题描述】:

是否可以创建属性名称包含破折号的对象?

我正在创建一个匿名对象,以便可以使用 Json.Net 将其序列化为 Json,并且我需要的属性之一包含一个“-”短划线字符。

我想要的一个例子是:

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

我知道我可以在创建对象时用下划线替换破折号,然后在序列化字符串中替换它们,但我想知道语言中是否有办法在没有这种解决方法的情况下做到这一点。

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    您不能对匿名对象执行此操作;字段名称必须是有效的标识符。您可以改为使用字典,Json.Net 应该像匿名对象一样轻松地对其进行序列化:

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

    【讨论】:

      【解决方案2】:

      不在 C# 中,不。然而,大多数序列化程序允许您自定义它 - 通常通过属性。带有 JSON.NET 的 IIRC,您希望 [JsonProperty("starts-with")] 指定名称。但是,您不能在匿名类型上使用属性,因此您可能需要使用所需的属性(和属性)定义一个类。

      【讨论】:

      • 我喜欢这种非 c# 兼容名称的方法
      【解决方案3】:

      很遗憾,这是不可能的,因为语言无法区分以下两种表达方式:

      condition.starts-with;    // Read "starts-with" property.
      condition.starts - with;  // Read "starts" property and subtract "with" variable.
      

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2013-09-25
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-13
        相关资源
        最近更新 更多