尝试解决Config类中的所有问题:
public class Config
{
public Config()
{
this.MyProperty2 = new List<int> { 4,5,6 };
}
public string MyProperty1 { get; set; }
public List<int> MyProperty2 {
get {
return this.MyProperty2;
}
set {
if(this.MyProperty2.Count > 0)
{
this.MyProperty2.Clear();
this.MyProperty2 = value;
}
}
}
}
,
这通常对我有用:
您可能会认为,如果发出“获取”请求,它将设置默认值。如果在“获取”之前完成“设置”,则只有在“值”为null时,属性才会获取默认值。
public class Config{
public string MyProperty1{ get; set; }
private List<int> myProperty2{ get; set; } ;
public List<int> MyProperty2{
get{
if (myProperty2 == null)
myProperty2 = new List<int> { 4,6 };
return myProperty2 ;
}
set{
myProperty2 = value;
}
}
}
,
您可以使用JsonConvert
中的Newtonsoft.Json
;
var setting = "{\"MyProperty1\": \"MyValue1\",\"MyProperty2\": [1,2,3]}";
var settingConfig = JsonConvert.DeserializeObject(setting);
和配置类
public class Config
{
public string MyProperty1 { get; set; }
[Newtonsoft.Json.JsonConverter(typeof(DefaultArrayConverter))]
public List<int> MyProperty2 { get; set; } = new List<int> { 4,6 };
}
在这里我写了一个客户JsonConverter。
public class DefaultArrayConverter : JsonConverter
{
public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
{
var value = serializer.Deserialize(reader,objectType);
return value;
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return false;
}
public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
工作正常,但我不确定为什么MyProperty2
的实现中有6个值。
,
基于上述评论之一的答案,并结合我的强迫性要求,不要在此留下不可接受的答案,
假设变量json
包含.json配置文件的内容:
var cfg = JsonConvert.DeserializeObject<Config>(json,new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
关键是ObjectCreationHandling
-序列化程序设置ObjectCreationHandling.Replace
代替默认值,而不是附加默认值。
查看更多here
本文链接:https://www.f2er.com/2933991.html