带有命名元组的 JavaScriptSerializer

JavaScriptSerializer with named tuples

如果我将 JavaScriptSerializer 与命名元组一起使用,我会得到以下结果:

var serialized = new JavaScriptSerializer().Serialize((Foo: "Fooo", Bar: "Bar"));

序列化为:

{"Item1":"F","Item2":"B"}

任意选项获取:

{"Foo":"F","Bar":"B"}

没有编写自定义 class 属性 Foo 和 Bar 而不是元组?

您尝试过匿名 class 吗?

var serialized = new JavaScriptSerializer().SerializeObject(new {Foo= "Fooo", Bar= "Bar"});

它不适用于元组,因为:

public void M() {
    var t = (Foo:"fooo",Bar:"Baar");
}

在 IL 中被替换为:

.method public hidebysig 
    instance void M () cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 19 (0x13)
    .maxstack 3
    .locals init (
        [0] valuetype [mscorlib]System.ValueTuple`2<string, string>
    )

    IL_0000: nop
    IL_0001: ldloca.s 0
    IL_0003: ldstr "fooo"
    IL_0008: ldstr "Baar"
    IL_000d: call instance void valuetype [mscorlib]System.ValueTuple`2<string, string>::.ctor(!0, !1)
    IL_0012: ret
} // end of method C::M

如您所见,字段名称已从 IL 中消失,无法以任何方式检索(这只是语法糖)