1 回答
TA贡献1951条经验 获得超3个赞
尽管这可行,但这不是理想的解决方案。
您可以使用以下策略来暴露基类的某些属性,这些属性会扰乱自定义派生类中的顺序。
缺点是声明了一些基类的属性,但是如您所见,其背后的逻辑非常简单(get / set语法为C#7.0)。
using Newtonsoft.Json;
using System;
namespace JsonTest
{
public class Base
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 1, PropertyName = "A")]
public string A { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 2, PropertyName = "X")]
public string X { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 3, PropertyName = "B")]
public string B { get; set; }
}
public class Derived : Base
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 4, PropertyName = "C")]
public string C { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 5, PropertyName = "X")]
public new string X
{
get => base.X;
set => base.X = value;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 6, PropertyName = "D")]
public string D { get; set; }
}
class Program
{
static void Main(string[] args)
{
Base b = new Base() { A = "a", B = "b", X = "x" };
string serB = JsonConvert.SerializeObject(b);
Console.WriteLine($"Serialized base class:\r\n {serB}");
Derived d = new Derived() { A = "a", B = "b", C = "c", D = "d", X = "x" };
string serD = JsonConvert.SerializeObject(d);
Console.WriteLine($"Serialized derived class:\r\n {serD}");
}
}
}
输出:
Serialized base class:
{"A":"a","X":"x","B":"b"}
Serialized derived class:
{"A":"a","B":"b","C":"c","X":"x","D":"d"}
- 1 回答
- 0 关注
- 246 浏览
添加回答
举报