根据。 NET现在支持SerializableAttribute:
Json.NET现在发现,在这种类型的所有领域,无论是公共领域还是私人领域,都有可扩展的Attribute和序列号,忽略了这些特性。
下面的样本代码显示
Error getting value from CS$<>9__CachedAnonymousMethodDelegate1 on ConsoleApplication1.MyType .
如果我评论了WithLambda的财产,那么序列化就会如期成功。 事实上,我取得了以下成果:
- Leave [Serializable], leave TotalWithLambda: throws JsonSerializationException
- Leave [Serializable], remove TotalWithLambda: serializes "myList" only
- Remove [Serializable], leave TotalWithLambda: serializes "myList", "Total", and "TotalWithLambda"
- Remove [Serializable], remove TotalWithLambda: serializes "myList" and "Total"
I understand all of these cases except the first one. Why does the combination of [Serializable] and a read-only property with a lambda in it cause this exception?
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var foo = new MyType();
foo.myList = new List<int>() { 0, 1, 2, 3 };
var returnVal = JsonConvert.SerializeObject(foo);
Console.WriteLine("Return: " + returnVal.ToString());
Console.ReadKey();
}
}
[Serializable]
class MyType
{
public IList<int> myList;
public int Total { get { return this.myList.Sum(); } }
public int TotalWithLambda { get { return this.myList.Sum(x => x); } }
}
}