我有两个类,看起来像这样:
class BaseClass
{
public string Property1;
}
class ChildClass : BaseClass
{
public string Property2;
}
如果我创建 ChildClass 的实例,然后转换为 BaseClass 并 Json 序列化它,则 ChildClass 的属性就会显示。
ChildClass childInstance = new ChildClass() { Property1 = "1", Property2 = "2" };
BaseClass baseInstance = (BaseClass)childInstance;
Console.WriteLine(JsonConvert.SerializeObject(baseInstance, Formatting.Indented));
{
"Property2": "2",
"Property1": "1"
}
尽管事实上,Property2 无法从代码中的 baseInstance 访问。
为什么会发生这种情况?有好的解决办法吗?
最佳答案
SerializeObject
是一种非泛型方法,它采用 object
作为参数 - 然后它在内部使用 .GetType()
来发现对象是。因此:您在代码中考虑的类型并不重要;重要的是对象实际上是什么。从object
参数的角度来看:没有相关成员是直接可见的。这根本不是障碍。
关于c# - Newtonsoft 在基类的序列化中包含子属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69173263/