可能重复:
序列化静态类?
是否可以序列化类,例如:
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);