0

可能重复:
序列化静态类?

是否可以序列化类,例如:

public static class Foo
{
    public static int foo1 = 1;
    public static int foo2 = 2;
    public static string foo3 = "test";
}

在 C# 中使用 JsonSerializer 转换为 JSON?

如果我使用:

  JsonWriter jw = new JsonTextWriter(streamWriter)
  JsonSerializer serializer = new JsonSerializer();
  serializer.Serialize(jw, Foo);

出现错误: error CS0118: 'Example.Foo' is a 'type' but is used like a 'variable' 提前感谢您的任何回复。

@Update 序列化静态类是不可能的,但是你可以创建这个类的静态实例并序列化它。样本:

    public static FooClass Foo = new FooClass();
    [Serializable]
    public class FooClass : System.Runtime.Serialization.ISerializable
    {
        public FooClass()
        {

        }
        public static int foo1 = 1;
        public static int foo2 = 2;
        public static string foo3 = "test";

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("static.foo1", FooClass.foo1, typeof(int));
            info.AddValue("static.foo2", FooClass.foo2, typeof(int));
            info.AddValue("static.foo3", FooClass.foo3, typeof(string));
        }

        public FooClass(SerializationInfo info, StreamingContext context)
        {
            FooClass.foo1 = info.GetInt32("static.foo1");
            FooClass.foo2 = info.GetInt32("static.foo2");
            FooClass.foo3 = info.GetString("static.foo3");
        }
    }
    ...
    serializer.Serialize(jw, Foo);
4

1 回答 1

1

或者,如果你不想实现所有的序列化垃圾,你可以只序列化一个匿名类型:

JsonWriter jw = new JsonTextWriter(streamWriter)
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, 
    new {
        foo1 = Foo.foo1,
        foo2 = Foo.foo2,
        foo3 = Foo.foo3
    });
于 2012-12-28T16:40:04.613 回答