1 回答
TA贡献1876条经验 获得超5个赞
如果您不希望对象处于可能无效的状态,那么我首先建议将其设为不可变。
然后,您可以使用JsonConstructor验证:
public class ABTest
{
[JsonProperty(Required = Required.Always)]
public ulong CountOfAs { get; }
[JsonProperty(Required = Required.Always)]
public ulong CountOfBs { get; }
[JsonProperty(Required = Required.Always)]
public ulong TotalCount { get; }
[JsonProperty(Required = Required.Always)]
[JsonConverter(typeof(SomeCustomTypeJsonConverter))]
public SomeCustomType SomeOtherField { get; set; }
[JsonConstructor]
public ABTest(ulong countOfAs, ulong countOfBs, ulong totalCount, SomeCustomType someOtherField)
{
if (totalCount != countOfAs + countOfBs)
throw new ArgumentException(nameof(totalCount));
CountOfAs = countOfAs;
CountOfBs = countOfBs;
TotalCount = totalCount;
SomeOtherField = someOtherField;
}
}
这为您提供了一个构造函数,Json.NET 和您的代码库的其余部分都可以用于验证。
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报